blob: 5f03792b3ec7dcad13ace3004694ebfc0128a20a [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;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500138 PyObject *c_filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 struct symtable *c_st;
140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
141 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Georg Brandl8334fd92010-12-04 10:26:46 +0000143 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 int c_interactive; /* true if in interactive mode */
145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
149 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150};
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152static int compiler_enter_scope(struct compiler *, identifier, void *, int);
153static void compiler_free(struct compiler *);
154static basicblock *compiler_new_block(struct compiler *);
155static int compiler_next_instr(struct compiler *, basicblock *);
156static int compiler_addop(struct compiler *, int);
157static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
158static int compiler_addop_i(struct compiler *, int, int);
159static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160static basicblock *compiler_use_new_block(struct compiler *);
161static int compiler_error(struct compiler *, const char *);
162static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
163
164static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
165static int compiler_visit_stmt(struct compiler *, stmt_ty);
166static int compiler_visit_keyword(struct compiler *, keyword_ty);
167static int compiler_visit_expr(struct compiler *, expr_ty);
168static int compiler_augassign(struct compiler *, stmt_ty);
169static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
172static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176/* Returns true if there is a loop on the fblock stack. */
177static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178
179static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000180static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500182static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000183static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 asdl_seq *args,
185 asdl_seq *keywords,
186 expr_ty starargs,
187 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500188static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
Benjamin Petersonb173f782009-05-05 22:31:58 +0000193#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 /* Name mangling: __private becomes _classname__private.
199 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200200 PyObject *result;
201 size_t nlen, plen, ipriv;
202 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200204 PyUnicode_READ_CHAR(ident, 0) != '_' ||
205 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 Py_INCREF(ident);
207 return ident;
208 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200209 nlen = PyUnicode_GET_LENGTH(ident);
210 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 The only time a name with a dot can occur is when
214 we are compiling an import statement that has a
215 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 TODO(jhylton): Decide whether we want to support
218 mangling of the module name, e.g. __M.X.
219 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
221 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
222 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 Py_INCREF(ident);
224 return ident; /* Don't mangle __whatever__ */
225 }
226 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200227 ipriv = 0;
228 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
229 ipriv++;
230 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident; /* Don't mangle if class is just underscores */
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 assert(1 <= PY_SSIZE_T_MAX - nlen);
237 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200239 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
240 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
241 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
242
243 result = PyUnicode_New(1 + nlen + plen, maxchar);
244 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200246 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
247 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
248 PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen);
249 PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen);
250 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000251}
252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253static int
254compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 c->c_stack = PyList_New(0);
259 if (!c->c_stack)
260 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263}
264
265PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000266PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
267 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 struct compiler c;
270 PyCodeObject *co = NULL;
271 PyCompilerFlags local_flags;
272 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (!__doc__) {
275 __doc__ = PyUnicode_InternFromString("__doc__");
276 if (!__doc__)
277 return NULL;
278 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (!compiler_init(&c))
281 return NULL;
282 c.c_filename = filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500283 c.c_filename_obj = PyUnicode_DecodeFSDefault(filename);
284 if (!c.c_filename_obj)
285 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 c.c_arena = arena;
287 c.c_future = PyFuture_FromAST(mod, filename);
288 if (c.c_future == NULL)
289 goto finally;
290 if (!flags) {
291 local_flags.cf_flags = 0;
292 flags = &local_flags;
293 }
294 merged = c.c_future->ff_features | flags->cf_flags;
295 c.c_future->ff_features = merged;
296 flags->cf_flags = merged;
297 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000298 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 c.c_st = PySymtable_Build(mod, filename, c.c_future);
302 if (c.c_st == NULL) {
303 if (!PyErr_Occurred())
304 PyErr_SetString(PyExc_SystemError, "no symtable");
305 goto finally;
306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309
Thomas Wouters1175c432006-02-27 22:49:54 +0000310 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 compiler_free(&c);
312 assert(co || PyErr_Occurred());
313 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314}
315
316PyCodeObject *
317PyNode_Compile(struct _node *n, const char *filename)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 PyCodeObject *co = NULL;
320 mod_ty mod;
321 PyArena *arena = PyArena_New();
322 if (!arena)
323 return NULL;
324 mod = PyAST_FromNode(n, NULL, filename, arena);
325 if (mod)
326 co = PyAST_Compile(mod, filename, NULL, arena);
327 PyArena_Free(arena);
328 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000329}
330
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000331static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (c->c_st)
335 PySymtable_Free(c->c_st);
336 if (c->c_future)
337 PyObject_Free(c->c_future);
Benjamin Peterson43b06862011-05-27 09:08:01 -0500338 if (c->c_filename_obj)
339 Py_DECREF(c->c_filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000341}
342
Guido van Rossum79f25d91997-04-29 20:08:16 +0000343static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_ssize_t i, n;
347 PyObject *v, *k;
348 PyObject *dict = PyDict_New();
349 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 n = PyList_Size(list);
352 for (i = 0; i < n; i++) {
353 v = PyLong_FromLong(i);
354 if (!v) {
355 Py_DECREF(dict);
356 return NULL;
357 }
358 k = PyList_GET_ITEM(list, i);
359 k = PyTuple_Pack(2, k, k->ob_type);
360 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
361 Py_XDECREF(k);
362 Py_DECREF(v);
363 Py_DECREF(dict);
364 return NULL;
365 }
366 Py_DECREF(k);
367 Py_DECREF(v);
368 }
369 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370}
371
372/* Return new dict containing names from src that match scope(s).
373
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000374src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376values are integers, starting at offset and increasing by one for
377each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378*/
379
380static PyObject *
381dictbytype(PyObject *src, int scope_type, int flag, int offset)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t pos = 0, i = offset, scope;
384 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 assert(offset >= 0);
387 if (dest == NULL)
388 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 while (PyDict_Next(src, &pos, &k, &v)) {
391 /* XXX this should probably be a macro in symtable.h */
392 long vi;
393 assert(PyLong_Check(v));
394 vi = PyLong_AS_LONG(v);
395 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (scope == scope_type || vi & flag) {
398 PyObject *tuple, *item = PyLong_FromLong(i);
399 if (item == NULL) {
400 Py_DECREF(dest);
401 return NULL;
402 }
403 i++;
404 tuple = PyTuple_Pack(2, k, k->ob_type);
405 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
406 Py_DECREF(item);
407 Py_DECREF(dest);
408 Py_XDECREF(tuple);
409 return NULL;
410 }
411 Py_DECREF(item);
412 Py_DECREF(tuple);
413 }
414 }
415 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000416}
417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418static void
419compiler_unit_check(struct compiler_unit *u)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 basicblock *block;
422 for (block = u->u_blocks; block != NULL; block = block->b_list) {
423 assert((void *)block != (void *)0xcbcbcbcb);
424 assert((void *)block != (void *)0xfbfbfbfb);
425 assert((void *)block != (void *)0xdbdbdbdb);
426 if (block->b_instr != NULL) {
427 assert(block->b_ialloc > 0);
428 assert(block->b_iused > 0);
429 assert(block->b_ialloc >= block->b_iused);
430 }
431 else {
432 assert (block->b_iused == 0);
433 assert (block->b_ialloc == 0);
434 }
435 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436}
437
438static void
439compiler_unit_free(struct compiler_unit *u)
440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 compiler_unit_check(u);
444 b = u->u_blocks;
445 while (b != NULL) {
446 if (b->b_instr)
447 PyObject_Free((void *)b->b_instr);
448 next = b->b_list;
449 PyObject_Free((void *)b);
450 b = next;
451 }
452 Py_CLEAR(u->u_ste);
453 Py_CLEAR(u->u_name);
454 Py_CLEAR(u->u_consts);
455 Py_CLEAR(u->u_names);
456 Py_CLEAR(u->u_varnames);
457 Py_CLEAR(u->u_freevars);
458 Py_CLEAR(u->u_cellvars);
459 Py_CLEAR(u->u_private);
460 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461}
462
463static int
464compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
470 struct compiler_unit));
471 if (!u) {
472 PyErr_NoMemory();
473 return 0;
474 }
475 memset(u, 0, sizeof(struct compiler_unit));
476 u->u_argcount = 0;
477 u->u_kwonlyargcount = 0;
478 u->u_ste = PySymtable_Lookup(c->c_st, key);
479 if (!u->u_ste) {
480 compiler_unit_free(u);
481 return 0;
482 }
483 Py_INCREF(name);
484 u->u_name = name;
485 u->u_varnames = list2dict(u->u_ste->ste_varnames);
486 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
487 if (!u->u_varnames || !u->u_cellvars) {
488 compiler_unit_free(u);
489 return 0;
490 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
493 PyDict_Size(u->u_cellvars));
494 if (!u->u_freevars) {
495 compiler_unit_free(u);
496 return 0;
497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 u->u_blocks = NULL;
500 u->u_nfblocks = 0;
501 u->u_firstlineno = lineno;
502 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000503 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 u->u_lineno_set = 0;
505 u->u_consts = PyDict_New();
506 if (!u->u_consts) {
507 compiler_unit_free(u);
508 return 0;
509 }
510 u->u_names = PyDict_New();
511 if (!u->u_names) {
512 compiler_unit_free(u);
513 return 0;
514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Push the old compiler_unit on the stack. */
519 if (c->u) {
520 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
521 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
522 Py_XDECREF(capsule);
523 compiler_unit_free(u);
524 return 0;
525 }
526 Py_DECREF(capsule);
527 u->u_private = c->u->u_private;
528 Py_XINCREF(u->u_private);
529 }
530 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 c->c_nestlevel++;
533 if (compiler_use_new_block(c) == NULL)
534 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537}
538
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000539static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000540compiler_exit_scope(struct compiler *c)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 int n;
543 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 c->c_nestlevel--;
546 compiler_unit_free(c->u);
547 /* Restore c->u to the parent unit. */
548 n = PyList_GET_SIZE(c->c_stack) - 1;
549 if (n >= 0) {
550 capsule = PyList_GET_ITEM(c->c_stack, n);
551 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
552 assert(c->u);
553 /* we are deleting from a list so this really shouldn't fail */
554 if (PySequence_DelItem(c->c_stack, n) < 0)
555 Py_FatalError("compiler_exit_scope()");
556 compiler_unit_check(c->u);
557 }
558 else
559 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561}
562
563/* Allocate a new block and return a pointer to it.
564 Returns NULL on error.
565*/
566
567static basicblock *
568compiler_new_block(struct compiler *c)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 basicblock *b;
571 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 u = c->u;
574 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
575 if (b == NULL) {
576 PyErr_NoMemory();
577 return NULL;
578 }
579 memset((void *)b, 0, sizeof(basicblock));
580 /* Extend the singly linked list of blocks with new block. */
581 b->b_list = u->u_blocks;
582 u->u_blocks = b;
583 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584}
585
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000586static basicblock *
587compiler_use_new_block(struct compiler *c)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 basicblock *block = compiler_new_block(c);
590 if (block == NULL)
591 return NULL;
592 c->u->u_curblock = block;
593 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594}
595
596static basicblock *
597compiler_next_block(struct compiler *c)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 basicblock *block = compiler_new_block(c);
600 if (block == NULL)
601 return NULL;
602 c->u->u_curblock->b_next = block;
603 c->u->u_curblock = block;
604 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605}
606
607static basicblock *
608compiler_use_next_block(struct compiler *c, basicblock *block)
609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 assert(block != NULL);
611 c->u->u_curblock->b_next = block;
612 c->u->u_curblock = block;
613 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614}
615
616/* Returns the offset of the next instruction in the current block's
617 b_instr array. Resizes the b_instr as necessary.
618 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000619*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
621static int
622compiler_next_instr(struct compiler *c, basicblock *b)
623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 assert(b != NULL);
625 if (b->b_instr == NULL) {
626 b->b_instr = (struct instr *)PyObject_Malloc(
627 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
628 if (b->b_instr == NULL) {
629 PyErr_NoMemory();
630 return -1;
631 }
632 b->b_ialloc = DEFAULT_BLOCK_SIZE;
633 memset((char *)b->b_instr, 0,
634 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
635 }
636 else if (b->b_iused == b->b_ialloc) {
637 struct instr *tmp;
638 size_t oldsize, newsize;
639 oldsize = b->b_ialloc * sizeof(struct instr);
640 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (oldsize > (PY_SIZE_MAX >> 1)) {
643 PyErr_NoMemory();
644 return -1;
645 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (newsize == 0) {
648 PyErr_NoMemory();
649 return -1;
650 }
651 b->b_ialloc <<= 1;
652 tmp = (struct instr *)PyObject_Realloc(
653 (void *)b->b_instr, newsize);
654 if (tmp == NULL) {
655 PyErr_NoMemory();
656 return -1;
657 }
658 b->b_instr = tmp;
659 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
660 }
661 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662}
663
Christian Heimes2202f872008-02-06 14:31:34 +0000664/* Set the i_lineno member of the instruction at offset off if the
665 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000666 already been set. If it has been set, the call has no effect.
667
Christian Heimes2202f872008-02-06 14:31:34 +0000668 The line number is reset in the following cases:
669 - when entering a new scope
670 - on each statement
671 - on each expression that start a new line
672 - before the "except" clause
673 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676static void
677compiler_set_lineno(struct compiler *c, int off)
678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 basicblock *b;
680 if (c->u->u_lineno_set)
681 return;
682 c->u->u_lineno_set = 1;
683 b = c->u->u_curblock;
684 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000685}
686
687static int
688opcode_stack_effect(int opcode, int oparg)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 switch (opcode) {
691 case POP_TOP:
692 return -1;
693 case ROT_TWO:
694 case ROT_THREE:
695 return 0;
696 case DUP_TOP:
697 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000698 case DUP_TOP_TWO:
699 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 case UNARY_POSITIVE:
702 case UNARY_NEGATIVE:
703 case UNARY_NOT:
704 case UNARY_INVERT:
705 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 case SET_ADD:
708 case LIST_APPEND:
709 return -1;
710 case MAP_ADD:
711 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 case BINARY_POWER:
714 case BINARY_MULTIPLY:
715 case BINARY_MODULO:
716 case BINARY_ADD:
717 case BINARY_SUBTRACT:
718 case BINARY_SUBSCR:
719 case BINARY_FLOOR_DIVIDE:
720 case BINARY_TRUE_DIVIDE:
721 return -1;
722 case INPLACE_FLOOR_DIVIDE:
723 case INPLACE_TRUE_DIVIDE:
724 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 case INPLACE_ADD:
727 case INPLACE_SUBTRACT:
728 case INPLACE_MULTIPLY:
729 case INPLACE_MODULO:
730 return -1;
731 case STORE_SUBSCR:
732 return -3;
733 case STORE_MAP:
734 return -2;
735 case DELETE_SUBSCR:
736 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 case BINARY_LSHIFT:
739 case BINARY_RSHIFT:
740 case BINARY_AND:
741 case BINARY_XOR:
742 case BINARY_OR:
743 return -1;
744 case INPLACE_POWER:
745 return -1;
746 case GET_ITER:
747 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 case PRINT_EXPR:
750 return -1;
751 case LOAD_BUILD_CLASS:
752 return 1;
753 case INPLACE_LSHIFT:
754 case INPLACE_RSHIFT:
755 case INPLACE_AND:
756 case INPLACE_XOR:
757 case INPLACE_OR:
758 return -1;
759 case BREAK_LOOP:
760 return 0;
761 case SETUP_WITH:
762 return 7;
763 case WITH_CLEANUP:
764 return -1; /* XXX Sometimes more */
765 case STORE_LOCALS:
766 return -1;
767 case RETURN_VALUE:
768 return -1;
769 case IMPORT_STAR:
770 return -1;
771 case YIELD_VALUE:
772 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 case POP_BLOCK:
775 return 0;
776 case POP_EXCEPT:
777 return 0; /* -3 except if bad bytecode */
778 case END_FINALLY:
779 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 case STORE_NAME:
782 return -1;
783 case DELETE_NAME:
784 return 0;
785 case UNPACK_SEQUENCE:
786 return oparg-1;
787 case UNPACK_EX:
788 return (oparg&0xFF) + (oparg>>8);
789 case FOR_ITER:
790 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 case STORE_ATTR:
793 return -2;
794 case DELETE_ATTR:
795 return -1;
796 case STORE_GLOBAL:
797 return -1;
798 case DELETE_GLOBAL:
799 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 case LOAD_CONST:
801 return 1;
802 case LOAD_NAME:
803 return 1;
804 case BUILD_TUPLE:
805 case BUILD_LIST:
806 case BUILD_SET:
807 return 1-oparg;
808 case BUILD_MAP:
809 return 1;
810 case LOAD_ATTR:
811 return 0;
812 case COMPARE_OP:
813 return -1;
814 case IMPORT_NAME:
815 return -1;
816 case IMPORT_FROM:
817 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 case JUMP_FORWARD:
820 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
821 case JUMP_IF_FALSE_OR_POP: /* "" */
822 case JUMP_ABSOLUTE:
823 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 case POP_JUMP_IF_FALSE:
826 case POP_JUMP_IF_TRUE:
827 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 case LOAD_GLOBAL:
830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 case CONTINUE_LOOP:
833 return 0;
834 case SETUP_LOOP:
835 return 0;
836 case SETUP_EXCEPT:
837 case SETUP_FINALLY:
838 return 6; /* can push 3 values for the new exception
839 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 case LOAD_FAST:
842 return 1;
843 case STORE_FAST:
844 return -1;
845 case DELETE_FAST:
846 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 case RAISE_VARARGS:
849 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000850#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 case CALL_FUNCTION:
852 return -NARGS(oparg);
853 case CALL_FUNCTION_VAR:
854 case CALL_FUNCTION_KW:
855 return -NARGS(oparg)-1;
856 case CALL_FUNCTION_VAR_KW:
857 return -NARGS(oparg)-2;
858 case MAKE_FUNCTION:
859 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
860 case MAKE_CLOSURE:
861 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000862#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 case BUILD_SLICE:
864 if (oparg == 3)
865 return -2;
866 else
867 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 case LOAD_CLOSURE:
870 return 1;
871 case LOAD_DEREF:
872 return 1;
873 case STORE_DEREF:
874 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000875 case DELETE_DEREF:
876 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 default:
878 fprintf(stderr, "opcode = %d\n", opcode);
879 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 }
882 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000883}
884
885/* Add an opcode with no argument.
886 Returns 0 on failure, 1 on success.
887*/
888
889static int
890compiler_addop(struct compiler *c, int opcode)
891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 basicblock *b;
893 struct instr *i;
894 int off;
895 off = compiler_next_instr(c, c->u->u_curblock);
896 if (off < 0)
897 return 0;
898 b = c->u->u_curblock;
899 i = &b->b_instr[off];
900 i->i_opcode = opcode;
901 i->i_hasarg = 0;
902 if (opcode == RETURN_VALUE)
903 b->b_return = 1;
904 compiler_set_lineno(c, off);
905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906}
907
908static int
909compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 PyObject *t, *v;
912 Py_ssize_t arg;
913 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* necessary to make sure types aren't coerced (e.g., int and long) */
916 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
917 if (PyFloat_Check(o)) {
918 d = PyFloat_AS_DOUBLE(o);
919 /* all we need is to make the tuple different in either the 0.0
920 * or -0.0 case from all others, just to avoid the "coercion".
921 */
922 if (d == 0.0 && copysign(1.0, d) < 0.0)
923 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
924 else
925 t = PyTuple_Pack(2, o, o->ob_type);
926 }
927 else if (PyComplex_Check(o)) {
928 Py_complex z;
929 int real_negzero, imag_negzero;
930 /* For the complex case we must make complex(x, 0.)
931 different from complex(x, -0.) and complex(0., y)
932 different from complex(-0., y), for any x and y.
933 All four complex zeros must be distinguished.*/
934 z = PyComplex_AsCComplex(o);
935 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
936 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
937 if (real_negzero && imag_negzero) {
938 t = PyTuple_Pack(5, o, o->ob_type,
939 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 else if (imag_negzero) {
942 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 else if (real_negzero) {
945 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
946 }
947 else {
948 t = PyTuple_Pack(2, o, o->ob_type);
949 }
950 }
951 else {
952 t = PyTuple_Pack(2, o, o->ob_type);
953 }
954 if (t == NULL)
955 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 v = PyDict_GetItem(dict, t);
958 if (!v) {
959 if (PyErr_Occurred())
960 return -1;
961 arg = PyDict_Size(dict);
962 v = PyLong_FromLong(arg);
963 if (!v) {
964 Py_DECREF(t);
965 return -1;
966 }
967 if (PyDict_SetItem(dict, t, v) < 0) {
968 Py_DECREF(t);
969 Py_DECREF(v);
970 return -1;
971 }
972 Py_DECREF(v);
973 }
974 else
975 arg = PyLong_AsLong(v);
976 Py_DECREF(t);
977 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978}
979
980static int
981compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983{
984 int arg = compiler_add_o(c, dict, o);
985 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 return compiler_addop_i(c, opcode, arg);
988}
989
990static int
991compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993{
994 int arg;
995 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
996 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000997 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998 arg = compiler_add_o(c, dict, mangled);
999 Py_DECREF(mangled);
1000 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001001 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002 return compiler_addop_i(c, opcode, arg);
1003}
1004
1005/* Add an opcode with an integer argument.
1006 Returns 0 on failure, 1 on success.
1007*/
1008
1009static int
1010compiler_addop_i(struct compiler *c, int opcode, int oparg)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 struct instr *i;
1013 int off;
1014 off = compiler_next_instr(c, c->u->u_curblock);
1015 if (off < 0)
1016 return 0;
1017 i = &c->u->u_curblock->b_instr[off];
1018 i->i_opcode = opcode;
1019 i->i_oparg = oparg;
1020 i->i_hasarg = 1;
1021 compiler_set_lineno(c, off);
1022 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023}
1024
1025static int
1026compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 struct instr *i;
1029 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 assert(b != NULL);
1032 off = compiler_next_instr(c, c->u->u_curblock);
1033 if (off < 0)
1034 return 0;
1035 i = &c->u->u_curblock->b_instr[off];
1036 i->i_opcode = opcode;
1037 i->i_target = b;
1038 i->i_hasarg = 1;
1039 if (absolute)
1040 i->i_jabs = 1;
1041 else
1042 i->i_jrel = 1;
1043 compiler_set_lineno(c, off);
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045}
1046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1048 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 it as the current block. NEXT_BLOCK() also creates an implicit jump
1050 from the current block to the new block.
1051*/
1052
Thomas Wouters89f507f2006-12-13 04:49:30 +00001053/* The returns inside these macros make it impossible to decref objects
1054 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055*/
1056
1057
1058#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (compiler_use_new_block((C)) == NULL) \
1060 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061}
1062
1063#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (compiler_next_block((C)) == NULL) \
1065 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066}
1067
1068#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (!compiler_addop((C), (OP))) \
1070 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001073#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (!compiler_addop((C), (OP))) { \
1075 compiler_exit_scope(c); \
1076 return 0; \
1077 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078}
1079
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1082 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083}
1084
1085#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1087 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088}
1089
1090#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (!compiler_addop_i((C), (OP), (O))) \
1092 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093}
1094
1095#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (!compiler_addop_j((C), (OP), (O), 1)) \
1097 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098}
1099
1100#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (!compiler_addop_j((C), (OP), (O), 0)) \
1102 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103}
1104
1105/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1106 the ASDL name to synthesize the name of the C type and the visit function.
1107*/
1108
1109#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (!compiler_visit_ ## TYPE((C), (V))) \
1111 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112}
1113
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001114#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (!compiler_visit_ ## TYPE((C), (V))) { \
1116 compiler_exit_scope(c); \
1117 return 0; \
1118 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001119}
1120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (!compiler_visit_slice((C), (V), (CTX))) \
1123 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124}
1125
1126#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 int _i; \
1128 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1129 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1130 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1131 if (!compiler_visit_ ## TYPE((C), elt)) \
1132 return 0; \
1133 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134}
1135
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001136#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 int _i; \
1138 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1139 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1140 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1141 if (!compiler_visit_ ## TYPE((C), elt)) { \
1142 compiler_exit_scope(c); \
1143 return 0; \
1144 } \
1145 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001146}
1147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148static int
1149compiler_isdocstring(stmt_ty s)
1150{
1151 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001152 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 return s->v.Expr.value->kind == Str_kind;
1154}
1155
1156/* Compile a sequence of statements, checking for a docstring. */
1157
1158static int
1159compiler_body(struct compiler *c, asdl_seq *stmts)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 int i = 0;
1162 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (!asdl_seq_LEN(stmts))
1165 return 1;
1166 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001167 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 /* don't generate docstrings if -OO */
1169 i = 1;
1170 VISIT(c, expr, st->v.Expr.value);
1171 if (!compiler_nameop(c, __doc__, Store))
1172 return 0;
1173 }
1174 for (; i < asdl_seq_LEN(stmts); i++)
1175 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177}
1178
1179static PyCodeObject *
1180compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyCodeObject *co;
1183 int addNone = 1;
1184 static PyObject *module;
1185 if (!module) {
1186 module = PyUnicode_InternFromString("<module>");
1187 if (!module)
1188 return NULL;
1189 }
1190 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1191 if (!compiler_enter_scope(c, module, mod, 0))
1192 return NULL;
1193 switch (mod->kind) {
1194 case Module_kind:
1195 if (!compiler_body(c, mod->v.Module.body)) {
1196 compiler_exit_scope(c);
1197 return 0;
1198 }
1199 break;
1200 case Interactive_kind:
1201 c->c_interactive = 1;
1202 VISIT_SEQ_IN_SCOPE(c, stmt,
1203 mod->v.Interactive.body);
1204 break;
1205 case Expression_kind:
1206 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1207 addNone = 0;
1208 break;
1209 case Suite_kind:
1210 PyErr_SetString(PyExc_SystemError,
1211 "suite should not be possible");
1212 return 0;
1213 default:
1214 PyErr_Format(PyExc_SystemError,
1215 "module kind %d should not be possible",
1216 mod->kind);
1217 return 0;
1218 }
1219 co = assemble(c, addNone);
1220 compiler_exit_scope(c);
1221 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001222}
1223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224/* The test for LOCAL must come before the test for FREE in order to
1225 handle classes where name is both local and free. The local var is
1226 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001227*/
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229static int
1230get_ref_type(struct compiler *c, PyObject *name)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 int scope = PyST_GetScope(c->u->u_ste, name);
1233 if (scope == 0) {
1234 char buf[350];
1235 PyOS_snprintf(buf, sizeof(buf),
1236 "unknown scope for %.100s in %.100s(%s) in %s\n"
1237 "symbols: %s\nlocals: %s\nglobals: %s",
1238 PyBytes_AS_STRING(name),
1239 PyBytes_AS_STRING(c->u->u_name),
1240 PyObject_REPR(c->u->u_ste->ste_id),
1241 c->c_filename,
1242 PyObject_REPR(c->u->u_ste->ste_symbols),
1243 PyObject_REPR(c->u->u_varnames),
1244 PyObject_REPR(c->u->u_names)
1245 );
1246 Py_FatalError(buf);
1247 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static int
1253compiler_lookup_arg(PyObject *dict, PyObject *name)
1254{
1255 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001258 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001260 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001262 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001263 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266static int
1267compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 int i, free = PyCode_GetNumFree(co);
1270 if (free == 0) {
1271 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1272 ADDOP_I(c, MAKE_FUNCTION, args);
1273 return 1;
1274 }
1275 for (i = 0; i < free; ++i) {
1276 /* Bypass com_addop_varname because it will generate
1277 LOAD_DEREF but LOAD_CLOSURE is needed.
1278 */
1279 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1280 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 /* Special case: If a class contains a method with a
1283 free variable that has the same name as a method,
1284 the name will be considered free *and* local in the
1285 class. It should be handled by the closure, as
1286 well as by the normal name loookup logic.
1287 */
1288 reftype = get_ref_type(c, name);
1289 if (reftype == CELL)
1290 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1291 else /* (reftype == FREE) */
1292 arg = compiler_lookup_arg(c->u->u_freevars, name);
1293 if (arg == -1) {
1294 fprintf(stderr,
1295 "lookup %s in %s %d %d\n"
1296 "freevars of %s: %s\n",
1297 PyObject_REPR(name),
1298 PyBytes_AS_STRING(c->u->u_name),
1299 reftype, arg,
1300 _PyUnicode_AsString(co->co_name),
1301 PyObject_REPR(co->co_freevars));
1302 Py_FatalError("compiler_make_closure()");
1303 }
1304 ADDOP_I(c, LOAD_CLOSURE, arg);
1305 }
1306 ADDOP_I(c, BUILD_TUPLE, free);
1307 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1308 ADDOP_I(c, MAKE_CLOSURE, args);
1309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312static int
1313compiler_decorators(struct compiler *c, asdl_seq* decos)
1314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (!decos)
1318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1321 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1322 }
1323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324}
1325
1326static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001327compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 int i, default_count = 0;
1331 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1332 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1333 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1334 if (default_) {
1335 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1336 if (!compiler_visit_expr(c, default_)) {
1337 return -1;
1338 }
1339 default_count++;
1340 }
1341 }
1342 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001343}
1344
1345static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001346compiler_visit_argannotation(struct compiler *c, identifier id,
1347 expr_ty annotation, PyObject *names)
1348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (annotation) {
1350 VISIT(c, expr, annotation);
1351 if (PyList_Append(names, id))
1352 return -1;
1353 }
1354 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001355}
1356
1357static int
1358compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1359 PyObject *names)
1360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 int i, error;
1362 for (i = 0; i < asdl_seq_LEN(args); i++) {
1363 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1364 error = compiler_visit_argannotation(
1365 c,
1366 arg->arg,
1367 arg->annotation,
1368 names);
1369 if (error)
1370 return error;
1371 }
1372 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001373}
1374
1375static int
1376compiler_visit_annotations(struct compiler *c, arguments_ty args,
1377 expr_ty returns)
1378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* Push arg annotations and a list of the argument names. Return the #
1380 of items pushed. The expressions are evaluated out-of-order wrt the
1381 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1384 */
1385 static identifier return_str;
1386 PyObject *names;
1387 int len;
1388 names = PyList_New(0);
1389 if (!names)
1390 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (compiler_visit_argannotations(c, args->args, names))
1393 goto error;
1394 if (args->varargannotation &&
1395 compiler_visit_argannotation(c, args->vararg,
1396 args->varargannotation, names))
1397 goto error;
1398 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1399 goto error;
1400 if (args->kwargannotation &&
1401 compiler_visit_argannotation(c, args->kwarg,
1402 args->kwargannotation, names))
1403 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (!return_str) {
1406 return_str = PyUnicode_InternFromString("return");
1407 if (!return_str)
1408 goto error;
1409 }
1410 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1411 goto error;
1412 }
1413
1414 len = PyList_GET_SIZE(names);
1415 if (len > 65534) {
1416 /* len must fit in 16 bits, and len is incremented below */
1417 PyErr_SetString(PyExc_SyntaxError,
1418 "too many annotations");
1419 goto error;
1420 }
1421 if (len) {
1422 /* convert names to a tuple and place on stack */
1423 PyObject *elt;
1424 int i;
1425 PyObject *s = PyTuple_New(len);
1426 if (!s)
1427 goto error;
1428 for (i = 0; i < len; i++) {
1429 elt = PyList_GET_ITEM(names, i);
1430 Py_INCREF(elt);
1431 PyTuple_SET_ITEM(s, i, elt);
1432 }
1433 ADDOP_O(c, LOAD_CONST, s, consts);
1434 Py_DECREF(s);
1435 len++; /* include the just-pushed tuple */
1436 }
1437 Py_DECREF(names);
1438 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001439
1440error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_DECREF(names);
1442 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001443}
1444
1445static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446compiler_function(struct compiler *c, stmt_ty s)
1447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyCodeObject *co;
1449 PyObject *first_const = Py_None;
1450 arguments_ty args = s->v.FunctionDef.args;
1451 expr_ty returns = s->v.FunctionDef.returns;
1452 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1453 stmt_ty st;
1454 int i, n, docstring, kw_default_count = 0, arglength;
1455 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (!compiler_decorators(c, decos))
1460 return 0;
1461 if (args->kwonlyargs) {
1462 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1463 args->kw_defaults);
1464 if (res < 0)
1465 return 0;
1466 kw_default_count = res;
1467 }
1468 if (args->defaults)
1469 VISIT_SEQ(c, expr, args->defaults);
1470 num_annotations = compiler_visit_annotations(c, args, returns);
1471 if (num_annotations < 0)
1472 return 0;
1473 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1476 s->lineno))
1477 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1480 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001481 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 first_const = st->v.Expr.value->v.Str.s;
1483 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1484 compiler_exit_scope(c);
1485 return 0;
1486 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 c->u->u_argcount = asdl_seq_LEN(args->args);
1489 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1490 n = asdl_seq_LEN(s->v.FunctionDef.body);
1491 /* if there was a docstring, we need to skip the first statement */
1492 for (i = docstring; i < n; i++) {
1493 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1494 VISIT_IN_SCOPE(c, stmt, st);
1495 }
1496 co = assemble(c, 1);
1497 compiler_exit_scope(c);
1498 if (co == NULL)
1499 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 arglength = asdl_seq_LEN(args->defaults);
1502 arglength |= kw_default_count << 8;
1503 arglength |= num_annotations << 16;
1504 compiler_make_closure(c, co, arglength);
1505 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 /* decorators */
1508 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1509 ADDOP_I(c, CALL_FUNCTION, 1);
1510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513}
1514
1515static int
1516compiler_class(struct compiler *c, stmt_ty s)
1517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 PyCodeObject *co;
1519 PyObject *str;
1520 int i;
1521 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_decorators(c, decos))
1524 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* ultimately generate code for:
1527 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1528 where:
1529 <func> is a function/closure created from the class body;
1530 it has a single argument (__locals__) where the dict
1531 (or MutableSequence) representing the locals is passed
1532 <name> is the class name
1533 <bases> is the positional arguments and *varargs argument
1534 <keywords> is the keyword arguments and **kwds argument
1535 This borrows from compiler_call.
1536 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 /* 1. compile the class body into a code object */
1539 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1540 return 0;
1541 /* this block represents what we do in the new scope */
1542 {
1543 /* use the class name for name mangling */
1544 Py_INCREF(s->v.ClassDef.name);
1545 Py_XDECREF(c->u->u_private);
1546 c->u->u_private = s->v.ClassDef.name;
1547 /* force it to have one mandatory argument */
1548 c->u->u_argcount = 1;
1549 /* load the first argument (__locals__) ... */
1550 ADDOP_I(c, LOAD_FAST, 0);
1551 /* ... and store it into f_locals */
1552 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1553 /* load (global) __name__ ... */
1554 str = PyUnicode_InternFromString("__name__");
1555 if (!str || !compiler_nameop(c, str, Load)) {
1556 Py_XDECREF(str);
1557 compiler_exit_scope(c);
1558 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 Py_DECREF(str);
1561 /* ... and store it as __module__ */
1562 str = PyUnicode_InternFromString("__module__");
1563 if (!str || !compiler_nameop(c, str, Store)) {
1564 Py_XDECREF(str);
1565 compiler_exit_scope(c);
1566 return 0;
1567 }
1568 Py_DECREF(str);
1569 /* compile the body proper */
1570 if (!compiler_body(c, s->v.ClassDef.body)) {
1571 compiler_exit_scope(c);
1572 return 0;
1573 }
1574 /* return the (empty) __class__ cell */
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05001575 str = PyUnicode_InternFromString("@__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (str == NULL) {
1577 compiler_exit_scope(c);
1578 return 0;
1579 }
1580 i = compiler_lookup_arg(c->u->u_cellvars, str);
1581 Py_DECREF(str);
1582 if (i == -1) {
1583 /* This happens when nobody references the cell */
1584 PyErr_Clear();
1585 /* Return None */
1586 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1587 }
1588 else {
1589 /* Return the cell where to store __class__ */
1590 ADDOP_I(c, LOAD_CLOSURE, i);
1591 }
1592 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1593 /* create the code object */
1594 co = assemble(c, 1);
1595 }
1596 /* leave the new scope */
1597 compiler_exit_scope(c);
1598 if (co == NULL)
1599 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* 2. load the 'build_class' function */
1602 ADDOP(c, LOAD_BUILD_CLASS);
1603
1604 /* 3. load a function (or closure) made from the code object */
1605 compiler_make_closure(c, co, 0);
1606 Py_DECREF(co);
1607
1608 /* 4. load class name */
1609 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1610
1611 /* 5. generate the rest of the code for the call */
1612 if (!compiler_call_helper(c, 2,
1613 s->v.ClassDef.bases,
1614 s->v.ClassDef.keywords,
1615 s->v.ClassDef.starargs,
1616 s->v.ClassDef.kwargs))
1617 return 0;
1618
1619 /* 6. apply decorators */
1620 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1621 ADDOP_I(c, CALL_FUNCTION, 1);
1622 }
1623
1624 /* 7. store into <name> */
1625 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1626 return 0;
1627 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628}
1629
1630static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001631compiler_ifexp(struct compiler *c, expr_ty e)
1632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 basicblock *end, *next;
1634
1635 assert(e->kind == IfExp_kind);
1636 end = compiler_new_block(c);
1637 if (end == NULL)
1638 return 0;
1639 next = compiler_new_block(c);
1640 if (next == NULL)
1641 return 0;
1642 VISIT(c, expr, e->v.IfExp.test);
1643 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1644 VISIT(c, expr, e->v.IfExp.body);
1645 ADDOP_JREL(c, JUMP_FORWARD, end);
1646 compiler_use_next_block(c, next);
1647 VISIT(c, expr, e->v.IfExp.orelse);
1648 compiler_use_next_block(c, end);
1649 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001650}
1651
1652static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653compiler_lambda(struct compiler *c, expr_ty e)
1654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 PyCodeObject *co;
1656 static identifier name;
1657 int kw_default_count = 0, arglength;
1658 arguments_ty args = e->v.Lambda.args;
1659 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (!name) {
1662 name = PyUnicode_InternFromString("<lambda>");
1663 if (!name)
1664 return 0;
1665 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (args->kwonlyargs) {
1668 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1669 args->kw_defaults);
1670 if (res < 0) return 0;
1671 kw_default_count = res;
1672 }
1673 if (args->defaults)
1674 VISIT_SEQ(c, expr, args->defaults);
1675 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1676 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* Make None the first constant, so the lambda can't have a
1679 docstring. */
1680 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1681 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 c->u->u_argcount = asdl_seq_LEN(args->args);
1684 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1685 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1686 if (c->u->u_ste->ste_generator) {
1687 ADDOP_IN_SCOPE(c, POP_TOP);
1688 }
1689 else {
1690 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1691 }
1692 co = assemble(c, 1);
1693 compiler_exit_scope(c);
1694 if (co == NULL)
1695 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 arglength = asdl_seq_LEN(args->defaults);
1698 arglength |= kw_default_count << 8;
1699 compiler_make_closure(c, co, arglength);
1700 Py_DECREF(co);
1701
1702 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703}
1704
1705static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706compiler_if(struct compiler *c, stmt_ty s)
1707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 basicblock *end, *next;
1709 int constant;
1710 assert(s->kind == If_kind);
1711 end = compiler_new_block(c);
1712 if (end == NULL)
1713 return 0;
1714
Georg Brandl8334fd92010-12-04 10:26:46 +00001715 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* constant = 0: "if 0"
1717 * constant = 1: "if 1", "if 2", ...
1718 * constant = -1: rest */
1719 if (constant == 0) {
1720 if (s->v.If.orelse)
1721 VISIT_SEQ(c, stmt, s->v.If.orelse);
1722 } else if (constant == 1) {
1723 VISIT_SEQ(c, stmt, s->v.If.body);
1724 } else {
1725 if (s->v.If.orelse) {
1726 next = compiler_new_block(c);
1727 if (next == NULL)
1728 return 0;
1729 }
1730 else
1731 next = end;
1732 VISIT(c, expr, s->v.If.test);
1733 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1734 VISIT_SEQ(c, stmt, s->v.If.body);
1735 ADDOP_JREL(c, JUMP_FORWARD, end);
1736 if (s->v.If.orelse) {
1737 compiler_use_next_block(c, next);
1738 VISIT_SEQ(c, stmt, s->v.If.orelse);
1739 }
1740 }
1741 compiler_use_next_block(c, end);
1742 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743}
1744
1745static int
1746compiler_for(struct compiler *c, stmt_ty s)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 start = compiler_new_block(c);
1751 cleanup = compiler_new_block(c);
1752 end = compiler_new_block(c);
1753 if (start == NULL || end == NULL || cleanup == NULL)
1754 return 0;
1755 ADDOP_JREL(c, SETUP_LOOP, end);
1756 if (!compiler_push_fblock(c, LOOP, start))
1757 return 0;
1758 VISIT(c, expr, s->v.For.iter);
1759 ADDOP(c, GET_ITER);
1760 compiler_use_next_block(c, start);
1761 ADDOP_JREL(c, FOR_ITER, cleanup);
1762 VISIT(c, expr, s->v.For.target);
1763 VISIT_SEQ(c, stmt, s->v.For.body);
1764 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1765 compiler_use_next_block(c, cleanup);
1766 ADDOP(c, POP_BLOCK);
1767 compiler_pop_fblock(c, LOOP, start);
1768 VISIT_SEQ(c, stmt, s->v.For.orelse);
1769 compiler_use_next_block(c, end);
1770 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771}
1772
1773static int
1774compiler_while(struct compiler *c, stmt_ty s)
1775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001777 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 if (constant == 0) {
1780 if (s->v.While.orelse)
1781 VISIT_SEQ(c, stmt, s->v.While.orelse);
1782 return 1;
1783 }
1784 loop = compiler_new_block(c);
1785 end = compiler_new_block(c);
1786 if (constant == -1) {
1787 anchor = compiler_new_block(c);
1788 if (anchor == NULL)
1789 return 0;
1790 }
1791 if (loop == NULL || end == NULL)
1792 return 0;
1793 if (s->v.While.orelse) {
1794 orelse = compiler_new_block(c);
1795 if (orelse == NULL)
1796 return 0;
1797 }
1798 else
1799 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 ADDOP_JREL(c, SETUP_LOOP, end);
1802 compiler_use_next_block(c, loop);
1803 if (!compiler_push_fblock(c, LOOP, loop))
1804 return 0;
1805 if (constant == -1) {
1806 VISIT(c, expr, s->v.While.test);
1807 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1808 }
1809 VISIT_SEQ(c, stmt, s->v.While.body);
1810 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* XXX should the two POP instructions be in a separate block
1813 if there is no else clause ?
1814 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (constant == -1) {
1817 compiler_use_next_block(c, anchor);
1818 ADDOP(c, POP_BLOCK);
1819 }
1820 compiler_pop_fblock(c, LOOP, loop);
1821 if (orelse != NULL) /* what if orelse is just pass? */
1822 VISIT_SEQ(c, stmt, s->v.While.orelse);
1823 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826}
1827
1828static int
1829compiler_continue(struct compiler *c)
1830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1832 static const char IN_FINALLY_ERROR_MSG[] =
1833 "'continue' not supported inside 'finally' clause";
1834 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (!c->u->u_nfblocks)
1837 return compiler_error(c, LOOP_ERROR_MSG);
1838 i = c->u->u_nfblocks - 1;
1839 switch (c->u->u_fblock[i].fb_type) {
1840 case LOOP:
1841 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1842 break;
1843 case EXCEPT:
1844 case FINALLY_TRY:
1845 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1846 /* Prevent continue anywhere under a finally
1847 even if hidden in a sub-try or except. */
1848 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1849 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1850 }
1851 if (i == -1)
1852 return compiler_error(c, LOOP_ERROR_MSG);
1853 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1854 break;
1855 case FINALLY_END:
1856 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860}
1861
1862/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863
1864 SETUP_FINALLY L
1865 <code for body>
1866 POP_BLOCK
1867 LOAD_CONST <None>
1868 L: <code for finalbody>
1869 END_FINALLY
1870
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 The special instructions use the block stack. Each block
1872 stack entry contains the instruction that created it (here
1873 SETUP_FINALLY), the level of the value stack at the time the
1874 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 Pushes the current value stack level and the label
1878 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 Pops en entry from the block stack, and pops the value
1881 stack until its level is the same as indicated on the
1882 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 Pops a variable number of entries from the *value* stack
1885 and re-raises the exception they specify. The number of
1886 entries popped depends on the (pseudo) exception type.
1887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888 The block stack is unwound when an exception is raised:
1889 when a SETUP_FINALLY entry is found, the exception is pushed
1890 onto the value stack (and the exception condition is cleared),
1891 and the interpreter jumps to the label gotten from the block
1892 stack.
1893*/
1894
1895static int
1896compiler_try_finally(struct compiler *c, stmt_ty s)
1897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 basicblock *body, *end;
1899 body = compiler_new_block(c);
1900 end = compiler_new_block(c);
1901 if (body == NULL || end == NULL)
1902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 ADDOP_JREL(c, SETUP_FINALLY, end);
1905 compiler_use_next_block(c, body);
1906 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1907 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05001908 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
1909 if (!compiler_try_except(c, s))
1910 return 0;
1911 }
1912 else {
1913 VISIT_SEQ(c, stmt, s->v.Try.body);
1914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 ADDOP(c, POP_BLOCK);
1916 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1919 compiler_use_next_block(c, end);
1920 if (!compiler_push_fblock(c, FINALLY_END, end))
1921 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05001922 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 ADDOP(c, END_FINALLY);
1924 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927}
1928
1929/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001930 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 (The contents of the value stack is shown in [], with the top
1932 at the right; 'tb' is trace-back info, 'val' the exception's
1933 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934
1935 Value stack Label Instruction Argument
1936 [] SETUP_EXCEPT L1
1937 [] <code for S>
1938 [] POP_BLOCK
1939 [] JUMP_FORWARD L0
1940
1941 [tb, val, exc] L1: DUP )
1942 [tb, val, exc, exc] <evaluate E1> )
1943 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1944 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1945 [tb, val, exc] POP
1946 [tb, val] <assign to V1> (or POP if no V1)
1947 [tb] POP
1948 [] <code for S1>
1949 JUMP_FORWARD L0
1950
1951 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 .............................etc.......................
1953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1955
1956 [] L0: <next statement>
1957
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 Of course, parts are not generated if Vi or Ei is not present.
1959*/
1960static int
1961compiler_try_except(struct compiler *c, stmt_ty s)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 basicblock *body, *orelse, *except, *end;
1964 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 body = compiler_new_block(c);
1967 except = compiler_new_block(c);
1968 orelse = compiler_new_block(c);
1969 end = compiler_new_block(c);
1970 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1971 return 0;
1972 ADDOP_JREL(c, SETUP_EXCEPT, except);
1973 compiler_use_next_block(c, body);
1974 if (!compiler_push_fblock(c, EXCEPT, body))
1975 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05001976 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 ADDOP(c, POP_BLOCK);
1978 compiler_pop_fblock(c, EXCEPT, body);
1979 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05001980 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 compiler_use_next_block(c, except);
1982 for (i = 0; i < n; i++) {
1983 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05001984 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (!handler->v.ExceptHandler.type && i < n-1)
1986 return compiler_error(c, "default 'except:' must be last");
1987 c->u->u_lineno_set = 0;
1988 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00001989 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 except = compiler_new_block(c);
1991 if (except == NULL)
1992 return 0;
1993 if (handler->v.ExceptHandler.type) {
1994 ADDOP(c, DUP_TOP);
1995 VISIT(c, expr, handler->v.ExceptHandler.type);
1996 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1997 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1998 }
1999 ADDOP(c, POP_TOP);
2000 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002001 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002002
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002003 cleanup_end = compiler_new_block(c);
2004 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002005 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002006 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002007
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002008 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2009 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002011 /*
2012 try:
2013 # body
2014 except type as name:
2015 try:
2016 # body
2017 finally:
2018 name = None
2019 del name
2020 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002022 /* second try: */
2023 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2024 compiler_use_next_block(c, cleanup_body);
2025 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2026 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002028 /* second # body */
2029 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2030 ADDOP(c, POP_BLOCK);
2031 ADDOP(c, POP_EXCEPT);
2032 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002034 /* finally: */
2035 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2036 compiler_use_next_block(c, cleanup_end);
2037 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2038 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002040 /* name = None */
2041 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2042 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002044 /* del name */
2045 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002047 ADDOP(c, END_FINALLY);
2048 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 }
2050 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002051 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002053 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002054 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002055 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056
Guido van Rossumb940e112007-01-10 16:19:56 +00002057 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002058 ADDOP(c, POP_TOP);
2059 compiler_use_next_block(c, cleanup_body);
2060 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2061 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002063 ADDOP(c, POP_EXCEPT);
2064 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
2066 ADDOP_JREL(c, JUMP_FORWARD, end);
2067 compiler_use_next_block(c, except);
2068 }
2069 ADDOP(c, END_FINALLY);
2070 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002071 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 compiler_use_next_block(c, end);
2073 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074}
2075
2076static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002077compiler_try(struct compiler *c, stmt_ty s) {
2078 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2079 return compiler_try_finally(c, s);
2080 else
2081 return compiler_try_except(c, s);
2082}
2083
2084
2085static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086compiler_import_as(struct compiler *c, identifier name, identifier asname)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* The IMPORT_NAME opcode was already generated. This function
2089 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 If there is a dot in name, we need to split it and emit a
2092 LOAD_ATTR for each name.
2093 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002094 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2095 PyUnicode_GET_LENGTH(name), 1);
2096 if (dot == -2)
2097 return -1;
2098 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002100 Py_ssize_t pos = dot + 1;
2101 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002103 dot = PyUnicode_FindChar(name, '.', pos,
2104 PyUnicode_GET_LENGTH(name), 1);
2105 if (dot == -2)
2106 return -1;
2107 attr = PyUnicode_Substring(name, pos,
2108 (dot != -1) ? dot :
2109 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (!attr)
2111 return -1;
2112 ADDOP_O(c, LOAD_ATTR, attr, names);
2113 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002114 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 }
2116 }
2117 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118}
2119
2120static int
2121compiler_import(struct compiler *c, stmt_ty s)
2122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* The Import node stores a module name like a.b.c as a single
2124 string. This is convenient for all cases except
2125 import a.b.c as d
2126 where we need to parse that string to extract the individual
2127 module names.
2128 XXX Perhaps change the representation to make this case simpler?
2129 */
2130 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 for (i = 0; i < n; i++) {
2133 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2134 int r;
2135 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 level = PyLong_FromLong(0);
2138 if (level == NULL)
2139 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 ADDOP_O(c, LOAD_CONST, level, consts);
2142 Py_DECREF(level);
2143 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2144 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (alias->asname) {
2147 r = compiler_import_as(c, alias->name, alias->asname);
2148 if (!r)
2149 return r;
2150 }
2151 else {
2152 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002153 Py_ssize_t dot = PyUnicode_FindChar(
2154 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2155 if (dot != -1)
2156 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 Py_DECREF(tmp);
2160 }
2161 if (!r)
2162 return r;
2163 }
2164 }
2165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166}
2167
2168static int
2169compiler_from_import(struct compiler *c, stmt_ty s)
2170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyObject *names = PyTuple_New(n);
2174 PyObject *level;
2175 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (!empty_string) {
2178 empty_string = PyUnicode_FromString("");
2179 if (!empty_string)
2180 return 0;
2181 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (!names)
2184 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 level = PyLong_FromLong(s->v.ImportFrom.level);
2187 if (!level) {
2188 Py_DECREF(names);
2189 return 0;
2190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 /* build up the names */
2193 for (i = 0; i < n; i++) {
2194 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2195 Py_INCREF(alias->name);
2196 PyTuple_SET_ITEM(names, i, alias->name);
2197 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2200 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2201 Py_DECREF(level);
2202 Py_DECREF(names);
2203 return compiler_error(c, "from __future__ imports must occur "
2204 "at the beginning of the file");
2205 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 ADDOP_O(c, LOAD_CONST, level, consts);
2208 Py_DECREF(level);
2209 ADDOP_O(c, LOAD_CONST, names, consts);
2210 Py_DECREF(names);
2211 if (s->v.ImportFrom.module) {
2212 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2213 }
2214 else {
2215 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2216 }
2217 for (i = 0; i < n; i++) {
2218 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2219 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 assert(n == 1);
2223 ADDOP(c, IMPORT_STAR);
2224 return 1;
2225 }
2226
2227 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2228 store_name = alias->name;
2229 if (alias->asname)
2230 store_name = alias->asname;
2231
2232 if (!compiler_nameop(c, store_name, Store)) {
2233 Py_DECREF(names);
2234 return 0;
2235 }
2236 }
2237 /* remove imported module */
2238 ADDOP(c, POP_TOP);
2239 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240}
2241
2242static int
2243compiler_assert(struct compiler *c, stmt_ty s)
2244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 static PyObject *assertion_error = NULL;
2246 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247
Georg Brandl8334fd92010-12-04 10:26:46 +00002248 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return 1;
2250 if (assertion_error == NULL) {
2251 assertion_error = PyUnicode_InternFromString("AssertionError");
2252 if (assertion_error == NULL)
2253 return 0;
2254 }
2255 if (s->v.Assert.test->kind == Tuple_kind &&
2256 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2257 const char* msg =
2258 "assertion is always true, perhaps remove parentheses?";
2259 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2260 c->u->u_lineno, NULL, NULL) == -1)
2261 return 0;
2262 }
2263 VISIT(c, expr, s->v.Assert.test);
2264 end = compiler_new_block(c);
2265 if (end == NULL)
2266 return 0;
2267 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2268 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2269 if (s->v.Assert.msg) {
2270 VISIT(c, expr, s->v.Assert.msg);
2271 ADDOP_I(c, CALL_FUNCTION, 1);
2272 }
2273 ADDOP_I(c, RAISE_VARARGS, 1);
2274 compiler_use_next_block(c, end);
2275 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276}
2277
2278static int
2279compiler_visit_stmt(struct compiler *c, stmt_ty s)
2280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Always assign a lineno to the next instruction for a stmt. */
2284 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002285 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 switch (s->kind) {
2289 case FunctionDef_kind:
2290 return compiler_function(c, s);
2291 case ClassDef_kind:
2292 return compiler_class(c, s);
2293 case Return_kind:
2294 if (c->u->u_ste->ste_type != FunctionBlock)
2295 return compiler_error(c, "'return' outside function");
2296 if (s->v.Return.value) {
2297 VISIT(c, expr, s->v.Return.value);
2298 }
2299 else
2300 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2301 ADDOP(c, RETURN_VALUE);
2302 break;
2303 case Delete_kind:
2304 VISIT_SEQ(c, expr, s->v.Delete.targets)
2305 break;
2306 case Assign_kind:
2307 n = asdl_seq_LEN(s->v.Assign.targets);
2308 VISIT(c, expr, s->v.Assign.value);
2309 for (i = 0; i < n; i++) {
2310 if (i < n - 1)
2311 ADDOP(c, DUP_TOP);
2312 VISIT(c, expr,
2313 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2314 }
2315 break;
2316 case AugAssign_kind:
2317 return compiler_augassign(c, s);
2318 case For_kind:
2319 return compiler_for(c, s);
2320 case While_kind:
2321 return compiler_while(c, s);
2322 case If_kind:
2323 return compiler_if(c, s);
2324 case Raise_kind:
2325 n = 0;
2326 if (s->v.Raise.exc) {
2327 VISIT(c, expr, s->v.Raise.exc);
2328 n++;
2329 if (s->v.Raise.cause) {
2330 VISIT(c, expr, s->v.Raise.cause);
2331 n++;
2332 }
2333 }
2334 ADDOP_I(c, RAISE_VARARGS, n);
2335 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002336 case Try_kind:
2337 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 case Assert_kind:
2339 return compiler_assert(c, s);
2340 case Import_kind:
2341 return compiler_import(c, s);
2342 case ImportFrom_kind:
2343 return compiler_from_import(c, s);
2344 case Global_kind:
2345 case Nonlocal_kind:
2346 break;
2347 case Expr_kind:
2348 if (c->c_interactive && c->c_nestlevel <= 1) {
2349 VISIT(c, expr, s->v.Expr.value);
2350 ADDOP(c, PRINT_EXPR);
2351 }
2352 else if (s->v.Expr.value->kind != Str_kind &&
2353 s->v.Expr.value->kind != Num_kind) {
2354 VISIT(c, expr, s->v.Expr.value);
2355 ADDOP(c, POP_TOP);
2356 }
2357 break;
2358 case Pass_kind:
2359 break;
2360 case Break_kind:
2361 if (!compiler_in_loop(c))
2362 return compiler_error(c, "'break' outside loop");
2363 ADDOP(c, BREAK_LOOP);
2364 break;
2365 case Continue_kind:
2366 return compiler_continue(c);
2367 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002368 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 }
2370 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371}
2372
2373static int
2374unaryop(unaryop_ty op)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 switch (op) {
2377 case Invert:
2378 return UNARY_INVERT;
2379 case Not:
2380 return UNARY_NOT;
2381 case UAdd:
2382 return UNARY_POSITIVE;
2383 case USub:
2384 return UNARY_NEGATIVE;
2385 default:
2386 PyErr_Format(PyExc_SystemError,
2387 "unary op %d should not be possible", op);
2388 return 0;
2389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390}
2391
2392static int
2393binop(struct compiler *c, operator_ty op)
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 switch (op) {
2396 case Add:
2397 return BINARY_ADD;
2398 case Sub:
2399 return BINARY_SUBTRACT;
2400 case Mult:
2401 return BINARY_MULTIPLY;
2402 case Div:
2403 return BINARY_TRUE_DIVIDE;
2404 case Mod:
2405 return BINARY_MODULO;
2406 case Pow:
2407 return BINARY_POWER;
2408 case LShift:
2409 return BINARY_LSHIFT;
2410 case RShift:
2411 return BINARY_RSHIFT;
2412 case BitOr:
2413 return BINARY_OR;
2414 case BitXor:
2415 return BINARY_XOR;
2416 case BitAnd:
2417 return BINARY_AND;
2418 case FloorDiv:
2419 return BINARY_FLOOR_DIVIDE;
2420 default:
2421 PyErr_Format(PyExc_SystemError,
2422 "binary op %d should not be possible", op);
2423 return 0;
2424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425}
2426
2427static int
2428cmpop(cmpop_ty op)
2429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 switch (op) {
2431 case Eq:
2432 return PyCmp_EQ;
2433 case NotEq:
2434 return PyCmp_NE;
2435 case Lt:
2436 return PyCmp_LT;
2437 case LtE:
2438 return PyCmp_LE;
2439 case Gt:
2440 return PyCmp_GT;
2441 case GtE:
2442 return PyCmp_GE;
2443 case Is:
2444 return PyCmp_IS;
2445 case IsNot:
2446 return PyCmp_IS_NOT;
2447 case In:
2448 return PyCmp_IN;
2449 case NotIn:
2450 return PyCmp_NOT_IN;
2451 default:
2452 return PyCmp_BAD;
2453 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454}
2455
2456static int
2457inplace_binop(struct compiler *c, operator_ty op)
2458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 switch (op) {
2460 case Add:
2461 return INPLACE_ADD;
2462 case Sub:
2463 return INPLACE_SUBTRACT;
2464 case Mult:
2465 return INPLACE_MULTIPLY;
2466 case Div:
2467 return INPLACE_TRUE_DIVIDE;
2468 case Mod:
2469 return INPLACE_MODULO;
2470 case Pow:
2471 return INPLACE_POWER;
2472 case LShift:
2473 return INPLACE_LSHIFT;
2474 case RShift:
2475 return INPLACE_RSHIFT;
2476 case BitOr:
2477 return INPLACE_OR;
2478 case BitXor:
2479 return INPLACE_XOR;
2480 case BitAnd:
2481 return INPLACE_AND;
2482 case FloorDiv:
2483 return INPLACE_FLOOR_DIVIDE;
2484 default:
2485 PyErr_Format(PyExc_SystemError,
2486 "inplace binary op %d should not be possible", op);
2487 return 0;
2488 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489}
2490
2491static int
2492compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 int op, scope, arg;
2495 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 PyObject *dict = c->u->u_names;
2498 PyObject *mangled;
2499 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 mangled = _Py_Mangle(c->u->u_private, name);
2502 if (!mangled)
2503 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 op = 0;
2506 optype = OP_NAME;
2507 scope = PyST_GetScope(c->u->u_ste, mangled);
2508 switch (scope) {
2509 case FREE:
2510 dict = c->u->u_freevars;
2511 optype = OP_DEREF;
2512 break;
2513 case CELL:
2514 dict = c->u->u_cellvars;
2515 optype = OP_DEREF;
2516 break;
2517 case LOCAL:
2518 if (c->u->u_ste->ste_type == FunctionBlock)
2519 optype = OP_FAST;
2520 break;
2521 case GLOBAL_IMPLICIT:
2522 if (c->u->u_ste->ste_type == FunctionBlock &&
2523 !c->u->u_ste->ste_unoptimized)
2524 optype = OP_GLOBAL;
2525 break;
2526 case GLOBAL_EXPLICIT:
2527 optype = OP_GLOBAL;
2528 break;
2529 default:
2530 /* scope can be 0 */
2531 break;
2532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 switch (optype) {
2538 case OP_DEREF:
2539 switch (ctx) {
2540 case Load: op = LOAD_DEREF; break;
2541 case Store: op = STORE_DEREF; break;
2542 case AugLoad:
2543 case AugStore:
2544 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002545 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 case Param:
2547 default:
2548 PyErr_SetString(PyExc_SystemError,
2549 "param invalid for deref variable");
2550 return 0;
2551 }
2552 break;
2553 case OP_FAST:
2554 switch (ctx) {
2555 case Load: op = LOAD_FAST; break;
2556 case Store: op = STORE_FAST; break;
2557 case Del: op = DELETE_FAST; break;
2558 case AugLoad:
2559 case AugStore:
2560 break;
2561 case Param:
2562 default:
2563 PyErr_SetString(PyExc_SystemError,
2564 "param invalid for local variable");
2565 return 0;
2566 }
2567 ADDOP_O(c, op, mangled, varnames);
2568 Py_DECREF(mangled);
2569 return 1;
2570 case OP_GLOBAL:
2571 switch (ctx) {
2572 case Load: op = LOAD_GLOBAL; break;
2573 case Store: op = STORE_GLOBAL; break;
2574 case Del: op = DELETE_GLOBAL; break;
2575 case AugLoad:
2576 case AugStore:
2577 break;
2578 case Param:
2579 default:
2580 PyErr_SetString(PyExc_SystemError,
2581 "param invalid for global variable");
2582 return 0;
2583 }
2584 break;
2585 case OP_NAME:
2586 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002587 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 case Store: op = STORE_NAME; break;
2589 case Del: op = DELETE_NAME; break;
2590 case AugLoad:
2591 case AugStore:
2592 break;
2593 case Param:
2594 default:
2595 PyErr_SetString(PyExc_SystemError,
2596 "param invalid for name variable");
2597 return 0;
2598 }
2599 break;
2600 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 assert(op);
2603 arg = compiler_add_o(c, dict, mangled);
2604 Py_DECREF(mangled);
2605 if (arg < 0)
2606 return 0;
2607 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608}
2609
2610static int
2611compiler_boolop(struct compiler *c, expr_ty e)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 basicblock *end;
2614 int jumpi, i, n;
2615 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 assert(e->kind == BoolOp_kind);
2618 if (e->v.BoolOp.op == And)
2619 jumpi = JUMP_IF_FALSE_OR_POP;
2620 else
2621 jumpi = JUMP_IF_TRUE_OR_POP;
2622 end = compiler_new_block(c);
2623 if (end == NULL)
2624 return 0;
2625 s = e->v.BoolOp.values;
2626 n = asdl_seq_LEN(s) - 1;
2627 assert(n >= 0);
2628 for (i = 0; i < n; ++i) {
2629 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2630 ADDOP_JABS(c, jumpi, end);
2631 }
2632 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2633 compiler_use_next_block(c, end);
2634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635}
2636
2637static int
2638compiler_list(struct compiler *c, expr_ty e)
2639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 int n = asdl_seq_LEN(e->v.List.elts);
2641 if (e->v.List.ctx == Store) {
2642 int i, seen_star = 0;
2643 for (i = 0; i < n; i++) {
2644 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2645 if (elt->kind == Starred_kind && !seen_star) {
2646 if ((i >= (1 << 8)) ||
2647 (n-i-1 >= (INT_MAX >> 8)))
2648 return compiler_error(c,
2649 "too many expressions in "
2650 "star-unpacking assignment");
2651 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2652 seen_star = 1;
2653 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2654 } else if (elt->kind == Starred_kind) {
2655 return compiler_error(c,
2656 "two starred expressions in assignment");
2657 }
2658 }
2659 if (!seen_star) {
2660 ADDOP_I(c, UNPACK_SEQUENCE, n);
2661 }
2662 }
2663 VISIT_SEQ(c, expr, e->v.List.elts);
2664 if (e->v.List.ctx == Load) {
2665 ADDOP_I(c, BUILD_LIST, n);
2666 }
2667 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668}
2669
2670static int
2671compiler_tuple(struct compiler *c, expr_ty e)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 int n = asdl_seq_LEN(e->v.Tuple.elts);
2674 if (e->v.Tuple.ctx == Store) {
2675 int i, seen_star = 0;
2676 for (i = 0; i < n; i++) {
2677 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2678 if (elt->kind == Starred_kind && !seen_star) {
2679 if ((i >= (1 << 8)) ||
2680 (n-i-1 >= (INT_MAX >> 8)))
2681 return compiler_error(c,
2682 "too many expressions in "
2683 "star-unpacking assignment");
2684 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2685 seen_star = 1;
2686 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2687 } else if (elt->kind == Starred_kind) {
2688 return compiler_error(c,
2689 "two starred expressions in assignment");
2690 }
2691 }
2692 if (!seen_star) {
2693 ADDOP_I(c, UNPACK_SEQUENCE, n);
2694 }
2695 }
2696 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2697 if (e->v.Tuple.ctx == Load) {
2698 ADDOP_I(c, BUILD_TUPLE, n);
2699 }
2700 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701}
2702
2703static int
2704compiler_compare(struct compiler *c, expr_ty e)
2705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 int i, n;
2707 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2710 VISIT(c, expr, e->v.Compare.left);
2711 n = asdl_seq_LEN(e->v.Compare.ops);
2712 assert(n > 0);
2713 if (n > 1) {
2714 cleanup = compiler_new_block(c);
2715 if (cleanup == NULL)
2716 return 0;
2717 VISIT(c, expr,
2718 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2719 }
2720 for (i = 1; i < n; i++) {
2721 ADDOP(c, DUP_TOP);
2722 ADDOP(c, ROT_THREE);
2723 ADDOP_I(c, COMPARE_OP,
2724 cmpop((cmpop_ty)(asdl_seq_GET(
2725 e->v.Compare.ops, i - 1))));
2726 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2727 NEXT_BLOCK(c);
2728 if (i < (n - 1))
2729 VISIT(c, expr,
2730 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2731 }
2732 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2733 ADDOP_I(c, COMPARE_OP,
2734 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2735 if (n > 1) {
2736 basicblock *end = compiler_new_block(c);
2737 if (end == NULL)
2738 return 0;
2739 ADDOP_JREL(c, JUMP_FORWARD, end);
2740 compiler_use_next_block(c, cleanup);
2741 ADDOP(c, ROT_TWO);
2742 ADDOP(c, POP_TOP);
2743 compiler_use_next_block(c, end);
2744 }
2745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746}
2747
2748static int
2749compiler_call(struct compiler *c, expr_ty e)
2750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 VISIT(c, expr, e->v.Call.func);
2752 return compiler_call_helper(c, 0,
2753 e->v.Call.args,
2754 e->v.Call.keywords,
2755 e->v.Call.starargs,
2756 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002757}
2758
2759/* shared code between compiler_call and compiler_class */
2760static int
2761compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 int n, /* Args already pushed */
2763 asdl_seq *args,
2764 asdl_seq *keywords,
2765 expr_ty starargs,
2766 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 n += asdl_seq_LEN(args);
2771 VISIT_SEQ(c, expr, args);
2772 if (keywords) {
2773 VISIT_SEQ(c, keyword, keywords);
2774 n |= asdl_seq_LEN(keywords) << 8;
2775 }
2776 if (starargs) {
2777 VISIT(c, expr, starargs);
2778 code |= 1;
2779 }
2780 if (kwargs) {
2781 VISIT(c, expr, kwargs);
2782 code |= 2;
2783 }
2784 switch (code) {
2785 case 0:
2786 ADDOP_I(c, CALL_FUNCTION, n);
2787 break;
2788 case 1:
2789 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2790 break;
2791 case 2:
2792 ADDOP_I(c, CALL_FUNCTION_KW, n);
2793 break;
2794 case 3:
2795 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2796 break;
2797 }
2798 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799}
2800
Nick Coghlan650f0d02007-04-15 12:05:43 +00002801
2802/* List and set comprehensions and generator expressions work by creating a
2803 nested function to perform the actual iteration. This means that the
2804 iteration variables don't leak into the current scope.
2805 The defined function is called immediately following its definition, with the
2806 result of that call being the result of the expression.
2807 The LC/SC version returns the populated container, while the GE version is
2808 flagged in symtable.c as a generator, so it returns the generator object
2809 when the function is called.
2810 This code *knows* that the loop cannot contain break, continue, or return,
2811 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2812
2813 Possible cleanups:
2814 - iterate over the generator sequence instead of using recursion
2815*/
2816
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818compiler_comprehension_generator(struct compiler *c,
2819 asdl_seq *generators, int gen_index,
2820 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 /* generate code for the iterator, then each of the ifs,
2823 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 comprehension_ty gen;
2826 basicblock *start, *anchor, *skip, *if_cleanup;
2827 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 start = compiler_new_block(c);
2830 skip = compiler_new_block(c);
2831 if_cleanup = compiler_new_block(c);
2832 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2835 anchor == NULL)
2836 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 if (gen_index == 0) {
2841 /* Receive outermost iter as an implicit argument */
2842 c->u->u_argcount = 1;
2843 ADDOP_I(c, LOAD_FAST, 0);
2844 }
2845 else {
2846 /* Sub-iter - calculate on the fly */
2847 VISIT(c, expr, gen->iter);
2848 ADDOP(c, GET_ITER);
2849 }
2850 compiler_use_next_block(c, start);
2851 ADDOP_JREL(c, FOR_ITER, anchor);
2852 NEXT_BLOCK(c);
2853 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 /* XXX this needs to be cleaned up...a lot! */
2856 n = asdl_seq_LEN(gen->ifs);
2857 for (i = 0; i < n; i++) {
2858 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2859 VISIT(c, expr, e);
2860 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2861 NEXT_BLOCK(c);
2862 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 if (++gen_index < asdl_seq_LEN(generators))
2865 if (!compiler_comprehension_generator(c,
2866 generators, gen_index,
2867 elt, val, type))
2868 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* only append after the last for generator */
2871 if (gen_index >= asdl_seq_LEN(generators)) {
2872 /* comprehension specific code */
2873 switch (type) {
2874 case COMP_GENEXP:
2875 VISIT(c, expr, elt);
2876 ADDOP(c, YIELD_VALUE);
2877 ADDOP(c, POP_TOP);
2878 break;
2879 case COMP_LISTCOMP:
2880 VISIT(c, expr, elt);
2881 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2882 break;
2883 case COMP_SETCOMP:
2884 VISIT(c, expr, elt);
2885 ADDOP_I(c, SET_ADD, gen_index + 1);
2886 break;
2887 case COMP_DICTCOMP:
2888 /* With 'd[k] = v', v is evaluated before k, so we do
2889 the same. */
2890 VISIT(c, expr, val);
2891 VISIT(c, expr, elt);
2892 ADDOP_I(c, MAP_ADD, gen_index + 1);
2893 break;
2894 default:
2895 return 0;
2896 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 compiler_use_next_block(c, skip);
2899 }
2900 compiler_use_next_block(c, if_cleanup);
2901 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2902 compiler_use_next_block(c, anchor);
2903
2904 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905}
2906
2907static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002908compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 PyCodeObject *co = NULL;
2912 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 outermost_iter = ((comprehension_ty)
2915 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2918 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 if (type != COMP_GENEXP) {
2921 int op;
2922 switch (type) {
2923 case COMP_LISTCOMP:
2924 op = BUILD_LIST;
2925 break;
2926 case COMP_SETCOMP:
2927 op = BUILD_SET;
2928 break;
2929 case COMP_DICTCOMP:
2930 op = BUILD_MAP;
2931 break;
2932 default:
2933 PyErr_Format(PyExc_SystemError,
2934 "unknown comprehension type %d", type);
2935 goto error_in_scope;
2936 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 ADDOP_I(c, op, 0);
2939 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 if (!compiler_comprehension_generator(c, generators, 0, elt,
2942 val, type))
2943 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 if (type != COMP_GENEXP) {
2946 ADDOP(c, RETURN_VALUE);
2947 }
2948
2949 co = assemble(c, 1);
2950 compiler_exit_scope(c);
2951 if (co == NULL)
2952 goto error;
2953
2954 if (!compiler_make_closure(c, co, 0))
2955 goto error;
2956 Py_DECREF(co);
2957
2958 VISIT(c, expr, outermost_iter);
2959 ADDOP(c, GET_ITER);
2960 ADDOP_I(c, CALL_FUNCTION, 1);
2961 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002962error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002964error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 Py_XDECREF(co);
2966 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002967}
2968
2969static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970compiler_genexp(struct compiler *c, expr_ty e)
2971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 static identifier name;
2973 if (!name) {
2974 name = PyUnicode_FromString("<genexpr>");
2975 if (!name)
2976 return 0;
2977 }
2978 assert(e->kind == GeneratorExp_kind);
2979 return compiler_comprehension(c, e, COMP_GENEXP, name,
2980 e->v.GeneratorExp.generators,
2981 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002985compiler_listcomp(struct compiler *c, expr_ty e)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 static identifier name;
2988 if (!name) {
2989 name = PyUnicode_FromString("<listcomp>");
2990 if (!name)
2991 return 0;
2992 }
2993 assert(e->kind == ListComp_kind);
2994 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2995 e->v.ListComp.generators,
2996 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002997}
2998
2999static int
3000compiler_setcomp(struct compiler *c, expr_ty e)
3001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 static identifier name;
3003 if (!name) {
3004 name = PyUnicode_FromString("<setcomp>");
3005 if (!name)
3006 return 0;
3007 }
3008 assert(e->kind == SetComp_kind);
3009 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3010 e->v.SetComp.generators,
3011 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003012}
3013
3014
3015static int
3016compiler_dictcomp(struct compiler *c, expr_ty e)
3017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 static identifier name;
3019 if (!name) {
3020 name = PyUnicode_FromString("<dictcomp>");
3021 if (!name)
3022 return 0;
3023 }
3024 assert(e->kind == DictComp_kind);
3025 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3026 e->v.DictComp.generators,
3027 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003028}
3029
3030
3031static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032compiler_visit_keyword(struct compiler *c, keyword_ty k)
3033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3035 VISIT(c, expr, k->value);
3036 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037}
3038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 whether they are true or false.
3041
3042 Return values: 1 for true, 0 for false, -1 for non-constant.
3043 */
3044
3045static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003046expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 char *id;
3049 switch (e->kind) {
3050 case Ellipsis_kind:
3051 return 1;
3052 case Num_kind:
3053 return PyObject_IsTrue(e->v.Num.n);
3054 case Str_kind:
3055 return PyObject_IsTrue(e->v.Str.s);
3056 case Name_kind:
3057 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003058 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 if (strcmp(id, "True") == 0) return 1;
3060 if (strcmp(id, "False") == 0) return 0;
3061 if (strcmp(id, "None") == 0) return 0;
3062 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003063 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 /* fall through */
3065 default:
3066 return -1;
3067 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068}
3069
Guido van Rossumc2e20742006-02-27 22:32:47 +00003070/*
3071 Implements the with statement from PEP 343.
3072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003074
3075 with EXPR as VAR:
3076 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077
Guido van Rossumc2e20742006-02-27 22:32:47 +00003078 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079
Thomas Wouters477c8d52006-05-27 19:21:47 +00003080 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 exit = context.__exit__ # not calling it
3082 value = context.__enter__()
3083 try:
3084 VAR = value # if VAR present in the syntax
3085 BLOCK
3086 finally:
3087 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003089 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091 exit(*exc)
3092 */
3093static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003094compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003095{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003096 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003097 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003098
3099 assert(s->kind == With_kind);
3100
Guido van Rossumc2e20742006-02-27 22:32:47 +00003101 block = compiler_new_block(c);
3102 finally = compiler_new_block(c);
3103 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003104 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003105
Thomas Wouters477c8d52006-05-27 19:21:47 +00003106 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003107 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003108 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003110 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003111 compiler_use_next_block(c, block);
3112 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003113 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003114 }
3115
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003116 if (item->optional_vars) {
3117 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003118 }
3119 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003121 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003122 }
3123
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003124 pos++;
3125 if (pos == asdl_seq_LEN(s->v.With.items))
3126 /* BLOCK code */
3127 VISIT_SEQ(c, stmt, s->v.With.body)
3128 else if (!compiler_with(c, s, pos))
3129 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003130
3131 /* End of try block; start the finally block */
3132 ADDOP(c, POP_BLOCK);
3133 compiler_pop_fblock(c, FINALLY_TRY, block);
3134
3135 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3136 compiler_use_next_block(c, finally);
3137 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003138 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003139
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003140 /* Finally block starts; context.__exit__ is on the stack under
3141 the exception or return information. Just issue our magic
3142 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003143 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003144
3145 /* Finally block ends. */
3146 ADDOP(c, END_FINALLY);
3147 compiler_pop_fblock(c, FINALLY_END, finally);
3148 return 1;
3149}
3150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151static int
3152compiler_visit_expr(struct compiler *c, expr_ty e)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 /* If expr e has a different line number than the last expr/stmt,
3157 set a new line number for the next instruction.
3158 */
3159 if (e->lineno > c->u->u_lineno) {
3160 c->u->u_lineno = e->lineno;
3161 c->u->u_lineno_set = 0;
3162 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003163 /* Updating the column offset is always harmless. */
3164 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 switch (e->kind) {
3166 case BoolOp_kind:
3167 return compiler_boolop(c, e);
3168 case BinOp_kind:
3169 VISIT(c, expr, e->v.BinOp.left);
3170 VISIT(c, expr, e->v.BinOp.right);
3171 ADDOP(c, binop(c, e->v.BinOp.op));
3172 break;
3173 case UnaryOp_kind:
3174 VISIT(c, expr, e->v.UnaryOp.operand);
3175 ADDOP(c, unaryop(e->v.UnaryOp.op));
3176 break;
3177 case Lambda_kind:
3178 return compiler_lambda(c, e);
3179 case IfExp_kind:
3180 return compiler_ifexp(c, e);
3181 case Dict_kind:
3182 n = asdl_seq_LEN(e->v.Dict.values);
3183 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3184 for (i = 0; i < n; i++) {
3185 VISIT(c, expr,
3186 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3187 VISIT(c, expr,
3188 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3189 ADDOP(c, STORE_MAP);
3190 }
3191 break;
3192 case Set_kind:
3193 n = asdl_seq_LEN(e->v.Set.elts);
3194 VISIT_SEQ(c, expr, e->v.Set.elts);
3195 ADDOP_I(c, BUILD_SET, n);
3196 break;
3197 case GeneratorExp_kind:
3198 return compiler_genexp(c, e);
3199 case ListComp_kind:
3200 return compiler_listcomp(c, e);
3201 case SetComp_kind:
3202 return compiler_setcomp(c, e);
3203 case DictComp_kind:
3204 return compiler_dictcomp(c, e);
3205 case Yield_kind:
3206 if (c->u->u_ste->ste_type != FunctionBlock)
3207 return compiler_error(c, "'yield' outside function");
3208 if (e->v.Yield.value) {
3209 VISIT(c, expr, e->v.Yield.value);
3210 }
3211 else {
3212 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3213 }
3214 ADDOP(c, YIELD_VALUE);
3215 break;
3216 case Compare_kind:
3217 return compiler_compare(c, e);
3218 case Call_kind:
3219 return compiler_call(c, e);
3220 case Num_kind:
3221 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3222 break;
3223 case Str_kind:
3224 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3225 break;
3226 case Bytes_kind:
3227 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3228 break;
3229 case Ellipsis_kind:
3230 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3231 break;
3232 /* The following exprs can be assignment targets. */
3233 case Attribute_kind:
3234 if (e->v.Attribute.ctx != AugStore)
3235 VISIT(c, expr, e->v.Attribute.value);
3236 switch (e->v.Attribute.ctx) {
3237 case AugLoad:
3238 ADDOP(c, DUP_TOP);
3239 /* Fall through to load */
3240 case Load:
3241 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3242 break;
3243 case AugStore:
3244 ADDOP(c, ROT_TWO);
3245 /* Fall through to save */
3246 case Store:
3247 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3248 break;
3249 case Del:
3250 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3251 break;
3252 case Param:
3253 default:
3254 PyErr_SetString(PyExc_SystemError,
3255 "param invalid in attribute expression");
3256 return 0;
3257 }
3258 break;
3259 case Subscript_kind:
3260 switch (e->v.Subscript.ctx) {
3261 case AugLoad:
3262 VISIT(c, expr, e->v.Subscript.value);
3263 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3264 break;
3265 case Load:
3266 VISIT(c, expr, e->v.Subscript.value);
3267 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3268 break;
3269 case AugStore:
3270 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3271 break;
3272 case Store:
3273 VISIT(c, expr, e->v.Subscript.value);
3274 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3275 break;
3276 case Del:
3277 VISIT(c, expr, e->v.Subscript.value);
3278 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3279 break;
3280 case Param:
3281 default:
3282 PyErr_SetString(PyExc_SystemError,
3283 "param invalid in subscript expression");
3284 return 0;
3285 }
3286 break;
3287 case Starred_kind:
3288 switch (e->v.Starred.ctx) {
3289 case Store:
3290 /* In all legitimate cases, the Starred node was already replaced
3291 * by compiler_list/compiler_tuple. XXX: is that okay? */
3292 return compiler_error(c,
3293 "starred assignment target must be in a list or tuple");
3294 default:
3295 return compiler_error(c,
3296 "can use starred expression only as assignment target");
3297 }
3298 break;
3299 case Name_kind:
3300 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3301 /* child nodes of List and Tuple will have expr_context set */
3302 case List_kind:
3303 return compiler_list(c, e);
3304 case Tuple_kind:
3305 return compiler_tuple(c, e);
3306 }
3307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308}
3309
3310static int
3311compiler_augassign(struct compiler *c, stmt_ty s)
3312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 expr_ty e = s->v.AugAssign.target;
3314 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 switch (e->kind) {
3319 case Attribute_kind:
3320 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3321 AugLoad, e->lineno, e->col_offset, c->c_arena);
3322 if (auge == NULL)
3323 return 0;
3324 VISIT(c, expr, auge);
3325 VISIT(c, expr, s->v.AugAssign.value);
3326 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3327 auge->v.Attribute.ctx = AugStore;
3328 VISIT(c, expr, auge);
3329 break;
3330 case Subscript_kind:
3331 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3332 AugLoad, e->lineno, e->col_offset, c->c_arena);
3333 if (auge == NULL)
3334 return 0;
3335 VISIT(c, expr, auge);
3336 VISIT(c, expr, s->v.AugAssign.value);
3337 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3338 auge->v.Subscript.ctx = AugStore;
3339 VISIT(c, expr, auge);
3340 break;
3341 case Name_kind:
3342 if (!compiler_nameop(c, e->v.Name.id, Load))
3343 return 0;
3344 VISIT(c, expr, s->v.AugAssign.value);
3345 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3346 return compiler_nameop(c, e->v.Name.id, Store);
3347 default:
3348 PyErr_Format(PyExc_SystemError,
3349 "invalid node type (%d) for augmented assignment",
3350 e->kind);
3351 return 0;
3352 }
3353 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003354}
3355
3356static int
3357compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 struct fblockinfo *f;
3360 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3361 PyErr_SetString(PyExc_SystemError,
3362 "too many statically nested blocks");
3363 return 0;
3364 }
3365 f = &c->u->u_fblock[c->u->u_nfblocks++];
3366 f->fb_type = t;
3367 f->fb_block = b;
3368 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369}
3370
3371static void
3372compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 struct compiler_unit *u = c->u;
3375 assert(u->u_nfblocks > 0);
3376 u->u_nfblocks--;
3377 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3378 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379}
3380
Thomas Wouters89f507f2006-12-13 04:49:30 +00003381static int
3382compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 int i;
3384 struct compiler_unit *u = c->u;
3385 for (i = 0; i < u->u_nfblocks; ++i) {
3386 if (u->u_fblock[i].fb_type == LOOP)
3387 return 1;
3388 }
3389 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003390}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003391/* Raises a SyntaxError and returns 0.
3392 If something goes wrong, a different exception may be raised.
3393*/
3394
3395static int
3396compiler_error(struct compiler *c, const char *errstr)
3397{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003398 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3402 if (!loc) {
3403 Py_INCREF(Py_None);
3404 loc = Py_None;
3405 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003406 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003407 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 if (!u)
3409 goto exit;
3410 v = Py_BuildValue("(zO)", errstr, u);
3411 if (!v)
3412 goto exit;
3413 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 Py_DECREF(loc);
3416 Py_XDECREF(u);
3417 Py_XDECREF(v);
3418 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003419}
3420
3421static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422compiler_handle_subscr(struct compiler *c, const char *kind,
3423 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* XXX this code is duplicated */
3428 switch (ctx) {
3429 case AugLoad: /* fall through to Load */
3430 case Load: op = BINARY_SUBSCR; break;
3431 case AugStore:/* fall through to Store */
3432 case Store: op = STORE_SUBSCR; break;
3433 case Del: op = DELETE_SUBSCR; break;
3434 case Param:
3435 PyErr_Format(PyExc_SystemError,
3436 "invalid %s kind %d in subscript\n",
3437 kind, ctx);
3438 return 0;
3439 }
3440 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003441 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 }
3443 else if (ctx == AugStore) {
3444 ADDOP(c, ROT_THREE);
3445 }
3446 ADDOP(c, op);
3447 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448}
3449
3450static int
3451compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 int n = 2;
3454 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 /* only handles the cases where BUILD_SLICE is emitted */
3457 if (s->v.Slice.lower) {
3458 VISIT(c, expr, s->v.Slice.lower);
3459 }
3460 else {
3461 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3462 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 if (s->v.Slice.upper) {
3465 VISIT(c, expr, s->v.Slice.upper);
3466 }
3467 else {
3468 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3469 }
3470
3471 if (s->v.Slice.step) {
3472 n++;
3473 VISIT(c, expr, s->v.Slice.step);
3474 }
3475 ADDOP_I(c, BUILD_SLICE, n);
3476 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477}
3478
3479static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3481 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 switch (s->kind) {
3484 case Slice_kind:
3485 return compiler_slice(c, s, ctx);
3486 case Index_kind:
3487 VISIT(c, expr, s->v.Index.value);
3488 break;
3489 case ExtSlice_kind:
3490 default:
3491 PyErr_SetString(PyExc_SystemError,
3492 "extended slice invalid in nested slice");
3493 return 0;
3494 }
3495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496}
3497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498static int
3499compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 char * kindname = NULL;
3502 switch (s->kind) {
3503 case Index_kind:
3504 kindname = "index";
3505 if (ctx != AugStore) {
3506 VISIT(c, expr, s->v.Index.value);
3507 }
3508 break;
3509 case Slice_kind:
3510 kindname = "slice";
3511 if (ctx != AugStore) {
3512 if (!compiler_slice(c, s, ctx))
3513 return 0;
3514 }
3515 break;
3516 case ExtSlice_kind:
3517 kindname = "extended slice";
3518 if (ctx != AugStore) {
3519 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3520 for (i = 0; i < n; i++) {
3521 slice_ty sub = (slice_ty)asdl_seq_GET(
3522 s->v.ExtSlice.dims, i);
3523 if (!compiler_visit_nested_slice(c, sub, ctx))
3524 return 0;
3525 }
3526 ADDOP_I(c, BUILD_TUPLE, n);
3527 }
3528 break;
3529 default:
3530 PyErr_Format(PyExc_SystemError,
3531 "invalid subscript kind %d", s->kind);
3532 return 0;
3533 }
3534 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535}
3536
Thomas Wouters89f507f2006-12-13 04:49:30 +00003537/* End of the compiler section, beginning of the assembler section */
3538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539/* do depth-first search of basic block graph, starting with block.
3540 post records the block indices in post-order.
3541
3542 XXX must handle implicit jumps from one block to next
3543*/
3544
Thomas Wouters89f507f2006-12-13 04:49:30 +00003545struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 PyObject *a_bytecode; /* string containing bytecode */
3547 int a_offset; /* offset into bytecode */
3548 int a_nblocks; /* number of reachable blocks */
3549 basicblock **a_postorder; /* list of blocks in dfs postorder */
3550 PyObject *a_lnotab; /* string containing lnotab */
3551 int a_lnotab_off; /* offset into lnotab */
3552 int a_lineno; /* last lineno of emitted instruction */
3553 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003554};
3555
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556static void
3557dfs(struct compiler *c, basicblock *b, struct assembler *a)
3558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 int i;
3560 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 if (b->b_seen)
3563 return;
3564 b->b_seen = 1;
3565 if (b->b_next != NULL)
3566 dfs(c, b->b_next, a);
3567 for (i = 0; i < b->b_iused; i++) {
3568 instr = &b->b_instr[i];
3569 if (instr->i_jrel || instr->i_jabs)
3570 dfs(c, instr->i_target, a);
3571 }
3572 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573}
3574
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003575static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 int i, target_depth;
3579 struct instr *instr;
3580 if (b->b_seen || b->b_startdepth >= depth)
3581 return maxdepth;
3582 b->b_seen = 1;
3583 b->b_startdepth = depth;
3584 for (i = 0; i < b->b_iused; i++) {
3585 instr = &b->b_instr[i];
3586 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3587 if (depth > maxdepth)
3588 maxdepth = depth;
3589 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3590 if (instr->i_jrel || instr->i_jabs) {
3591 target_depth = depth;
3592 if (instr->i_opcode == FOR_ITER) {
3593 target_depth = depth-2;
3594 } else if (instr->i_opcode == SETUP_FINALLY ||
3595 instr->i_opcode == SETUP_EXCEPT) {
3596 target_depth = depth+3;
3597 if (target_depth > maxdepth)
3598 maxdepth = target_depth;
3599 }
3600 maxdepth = stackdepth_walk(c, instr->i_target,
3601 target_depth, maxdepth);
3602 if (instr->i_opcode == JUMP_ABSOLUTE ||
3603 instr->i_opcode == JUMP_FORWARD) {
3604 goto out; /* remaining code is dead */
3605 }
3606 }
3607 }
3608 if (b->b_next)
3609 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 b->b_seen = 0;
3612 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613}
3614
3615/* Find the flow path that needs the largest stack. We assume that
3616 * cycles in the flow graph have no net effect on the stack depth.
3617 */
3618static int
3619stackdepth(struct compiler *c)
3620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 basicblock *b, *entryblock;
3622 entryblock = NULL;
3623 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3624 b->b_seen = 0;
3625 b->b_startdepth = INT_MIN;
3626 entryblock = b;
3627 }
3628 if (!entryblock)
3629 return 0;
3630 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631}
3632
3633static int
3634assemble_init(struct assembler *a, int nblocks, int firstlineno)
3635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 memset(a, 0, sizeof(struct assembler));
3637 a->a_lineno = firstlineno;
3638 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3639 if (!a->a_bytecode)
3640 return 0;
3641 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3642 if (!a->a_lnotab)
3643 return 0;
3644 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3645 PyErr_NoMemory();
3646 return 0;
3647 }
3648 a->a_postorder = (basicblock **)PyObject_Malloc(
3649 sizeof(basicblock *) * nblocks);
3650 if (!a->a_postorder) {
3651 PyErr_NoMemory();
3652 return 0;
3653 }
3654 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655}
3656
3657static void
3658assemble_free(struct assembler *a)
3659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 Py_XDECREF(a->a_bytecode);
3661 Py_XDECREF(a->a_lnotab);
3662 if (a->a_postorder)
3663 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664}
3665
3666/* Return the size of a basic block in bytes. */
3667
3668static int
3669instrsize(struct instr *instr)
3670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (!instr->i_hasarg)
3672 return 1; /* 1 byte for the opcode*/
3673 if (instr->i_oparg > 0xffff)
3674 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3675 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676}
3677
3678static int
3679blocksize(basicblock *b)
3680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 int i;
3682 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 for (i = 0; i < b->b_iused; i++)
3685 size += instrsize(&b->b_instr[i]);
3686 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687}
3688
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003689/* Appends a pair to the end of the line number table, a_lnotab, representing
3690 the instruction's bytecode offset and line number. See
3691 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003692
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 int d_bytecode, d_lineno;
3697 int len;
3698 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 d_bytecode = a->a_offset - a->a_lineno_off;
3701 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 assert(d_bytecode >= 0);
3704 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if(d_bytecode == 0 && d_lineno == 0)
3707 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 if (d_bytecode > 255) {
3710 int j, nbytes, ncodes = d_bytecode / 255;
3711 nbytes = a->a_lnotab_off + 2 * ncodes;
3712 len = PyBytes_GET_SIZE(a->a_lnotab);
3713 if (nbytes >= len) {
3714 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3715 len = nbytes;
3716 else if (len <= INT_MAX / 2)
3717 len *= 2;
3718 else {
3719 PyErr_NoMemory();
3720 return 0;
3721 }
3722 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3723 return 0;
3724 }
3725 lnotab = (unsigned char *)
3726 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3727 for (j = 0; j < ncodes; j++) {
3728 *lnotab++ = 255;
3729 *lnotab++ = 0;
3730 }
3731 d_bytecode -= ncodes * 255;
3732 a->a_lnotab_off += ncodes * 2;
3733 }
3734 assert(d_bytecode <= 255);
3735 if (d_lineno > 255) {
3736 int j, nbytes, ncodes = d_lineno / 255;
3737 nbytes = a->a_lnotab_off + 2 * ncodes;
3738 len = PyBytes_GET_SIZE(a->a_lnotab);
3739 if (nbytes >= len) {
3740 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3741 len = nbytes;
3742 else if (len <= INT_MAX / 2)
3743 len *= 2;
3744 else {
3745 PyErr_NoMemory();
3746 return 0;
3747 }
3748 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3749 return 0;
3750 }
3751 lnotab = (unsigned char *)
3752 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3753 *lnotab++ = d_bytecode;
3754 *lnotab++ = 255;
3755 d_bytecode = 0;
3756 for (j = 1; j < ncodes; j++) {
3757 *lnotab++ = 0;
3758 *lnotab++ = 255;
3759 }
3760 d_lineno -= ncodes * 255;
3761 a->a_lnotab_off += ncodes * 2;
3762 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 len = PyBytes_GET_SIZE(a->a_lnotab);
3765 if (a->a_lnotab_off + 2 >= len) {
3766 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3767 return 0;
3768 }
3769 lnotab = (unsigned char *)
3770 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 a->a_lnotab_off += 2;
3773 if (d_bytecode) {
3774 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003775 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 }
3777 else { /* First line of a block; def stmt, etc. */
3778 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003779 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 }
3781 a->a_lineno = i->i_lineno;
3782 a->a_lineno_off = a->a_offset;
3783 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003784}
3785
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786/* assemble_emit()
3787 Extend the bytecode with a new instruction.
3788 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003789*/
3790
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003791static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 int size, arg = 0, ext = 0;
3795 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3796 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 size = instrsize(i);
3799 if (i->i_hasarg) {
3800 arg = i->i_oparg;
3801 ext = arg >> 16;
3802 }
3803 if (i->i_lineno && !assemble_lnotab(a, i))
3804 return 0;
3805 if (a->a_offset + size >= len) {
3806 if (len > PY_SSIZE_T_MAX / 2)
3807 return 0;
3808 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3809 return 0;
3810 }
3811 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3812 a->a_offset += size;
3813 if (size == 6) {
3814 assert(i->i_hasarg);
3815 *code++ = (char)EXTENDED_ARG;
3816 *code++ = ext & 0xff;
3817 *code++ = ext >> 8;
3818 arg &= 0xffff;
3819 }
3820 *code++ = i->i_opcode;
3821 if (i->i_hasarg) {
3822 assert(size == 3 || size == 6);
3823 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003824 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 }
3826 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003827}
3828
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003829static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 basicblock *b;
3833 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3834 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 /* Compute the size of each block and fixup jump args.
3837 Replace block pointer with position in bytecode. */
3838 do {
3839 totsize = 0;
3840 for (i = a->a_nblocks - 1; i >= 0; i--) {
3841 b = a->a_postorder[i];
3842 bsize = blocksize(b);
3843 b->b_offset = totsize;
3844 totsize += bsize;
3845 }
3846 last_extended_arg_count = extended_arg_count;
3847 extended_arg_count = 0;
3848 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3849 bsize = b->b_offset;
3850 for (i = 0; i < b->b_iused; i++) {
3851 struct instr *instr = &b->b_instr[i];
3852 /* Relative jumps are computed relative to
3853 the instruction pointer after fetching
3854 the jump instruction.
3855 */
3856 bsize += instrsize(instr);
3857 if (instr->i_jabs)
3858 instr->i_oparg = instr->i_target->b_offset;
3859 else if (instr->i_jrel) {
3860 int delta = instr->i_target->b_offset - bsize;
3861 instr->i_oparg = delta;
3862 }
3863 else
3864 continue;
3865 if (instr->i_oparg > 0xffff)
3866 extended_arg_count++;
3867 }
3868 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 /* XXX: This is an awful hack that could hurt performance, but
3871 on the bright side it should work until we come up
3872 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 The issue is that in the first loop blocksize() is called
3875 which calls instrsize() which requires i_oparg be set
3876 appropriately. There is a bootstrap problem because
3877 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 So we loop until we stop seeing new EXTENDED_ARGs.
3880 The only EXTENDED_ARGs that could be popping up are
3881 ones in jump instructions. So this should converge
3882 fairly quickly.
3883 */
3884 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003885}
3886
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003887static PyObject *
3888dict_keys_inorder(PyObject *dict, int offset)
3889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 PyObject *tuple, *k, *v;
3891 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 tuple = PyTuple_New(size);
3894 if (tuple == NULL)
3895 return NULL;
3896 while (PyDict_Next(dict, &pos, &k, &v)) {
3897 i = PyLong_AS_LONG(v);
3898 /* The keys of the dictionary are tuples. (see compiler_add_o)
3899 The object we want is always first, though. */
3900 k = PyTuple_GET_ITEM(k, 0);
3901 Py_INCREF(k);
3902 assert((i - offset) < size);
3903 assert((i - offset) >= 0);
3904 PyTuple_SET_ITEM(tuple, i - offset, k);
3905 }
3906 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003907}
3908
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003909static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 PySTEntryObject *ste = c->u->u_ste;
3913 int flags = 0, n;
3914 if (ste->ste_type != ModuleBlock)
3915 flags |= CO_NEWLOCALS;
3916 if (ste->ste_type == FunctionBlock) {
3917 if (!ste->ste_unoptimized)
3918 flags |= CO_OPTIMIZED;
3919 if (ste->ste_nested)
3920 flags |= CO_NESTED;
3921 if (ste->ste_generator)
3922 flags |= CO_GENERATOR;
3923 if (ste->ste_varargs)
3924 flags |= CO_VARARGS;
3925 if (ste->ste_varkeywords)
3926 flags |= CO_VARKEYWORDS;
3927 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* (Only) inherit compilerflags in PyCF_MASK */
3930 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 n = PyDict_Size(c->u->u_freevars);
3933 if (n < 0)
3934 return -1;
3935 if (n == 0) {
3936 n = PyDict_Size(c->u->u_cellvars);
3937 if (n < 0)
3938 return -1;
3939 if (n == 0) {
3940 flags |= CO_NOFREE;
3941 }
3942 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003945}
3946
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947static PyCodeObject *
3948makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 PyObject *tmp;
3951 PyCodeObject *co = NULL;
3952 PyObject *consts = NULL;
3953 PyObject *names = NULL;
3954 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 nlocals = PyDict_Size(c->u->u_varnames);
3979 flags = compute_code_flags(c);
3980 if (flags < 0)
3981 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3984 if (!bytecode)
3985 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3988 if (!tmp)
3989 goto error;
3990 Py_DECREF(consts);
3991 consts = tmp;
3992
3993 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3994 nlocals, stackdepth(c), flags,
3995 bytecode, consts, names, varnames,
3996 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05003997 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 c->u->u_firstlineno,
3999 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004000 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 Py_XDECREF(consts);
4002 Py_XDECREF(names);
4003 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 Py_XDECREF(name);
4005 Py_XDECREF(freevars);
4006 Py_XDECREF(cellvars);
4007 Py_XDECREF(bytecode);
4008 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004009}
4010
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004011
4012/* For debugging purposes only */
4013#if 0
4014static void
4015dump_instr(const struct instr *i)
4016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 const char *jrel = i->i_jrel ? "jrel " : "";
4018 const char *jabs = i->i_jabs ? "jabs " : "";
4019 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 *arg = '\0';
4022 if (i->i_hasarg)
4023 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4026 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004027}
4028
4029static void
4030dump_basicblock(const basicblock *b)
4031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 const char *seen = b->b_seen ? "seen " : "";
4033 const char *b_return = b->b_return ? "return " : "";
4034 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4035 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4036 if (b->b_instr) {
4037 int i;
4038 for (i = 0; i < b->b_iused; i++) {
4039 fprintf(stderr, " [%02d] ", i);
4040 dump_instr(b->b_instr + i);
4041 }
4042 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004043}
4044#endif
4045
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004046static PyCodeObject *
4047assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 basicblock *b, *entryblock;
4050 struct assembler a;
4051 int i, j, nblocks;
4052 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 /* Make sure every block that falls off the end returns None.
4055 XXX NEXT_BLOCK() isn't quite right, because if the last
4056 block ends with a jump or return b_next shouldn't set.
4057 */
4058 if (!c->u->u_curblock->b_return) {
4059 NEXT_BLOCK(c);
4060 if (addNone)
4061 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4062 ADDOP(c, RETURN_VALUE);
4063 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 nblocks = 0;
4066 entryblock = NULL;
4067 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4068 nblocks++;
4069 entryblock = b;
4070 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 /* Set firstlineno if it wasn't explicitly set. */
4073 if (!c->u->u_firstlineno) {
4074 if (entryblock && entryblock->b_instr)
4075 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4076 else
4077 c->u->u_firstlineno = 1;
4078 }
4079 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4080 goto error;
4081 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 /* Can't modify the bytecode after computing jump offsets. */
4084 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 /* Emit code in reverse postorder from dfs. */
4087 for (i = a.a_nblocks - 1; i >= 0; i--) {
4088 b = a.a_postorder[i];
4089 for (j = 0; j < b->b_iused; j++)
4090 if (!assemble_emit(&a, &b->b_instr[j]))
4091 goto error;
4092 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4095 goto error;
4096 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4097 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 assemble_free(&a);
4102 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004103}
Georg Brandl8334fd92010-12-04 10:26:46 +00004104
4105#undef PyAST_Compile
4106PyAPI_FUNC(PyCodeObject *)
4107PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4108 PyArena *arena)
4109{
4110 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4111}
4112
4113