blob: 8abe50f4ca982e0bdeb3cebf1b82225f1f70d23c [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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
46 unsigned i_hasarg : 1;
47 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040095 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096 COMPILER_SCOPE_COMPREHENSION,
97};
98
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099/* The following items change on entry and exit of code blocks.
100 They must be saved and restored when returning to a block.
101*/
102struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400106 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100107 int u_scope_type;
108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 /* The following fields are dicts that map objects to
110 the index of them in co_XXX. The index is used as
111 the argument for opcodes that refer to those collections.
112 */
113 PyObject *u_consts; /* all constants */
114 PyObject *u_names; /* all names */
115 PyObject *u_varnames; /* local variables */
116 PyObject *u_cellvars; /* cell variables */
117 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
Victor Stinnerf8e32212013-11-19 23:56:34 +0100121 Py_ssize_t u_argcount; /* number of arguments for block */
122 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 /* Pointer to the most recently allocated block. By following b_list
124 members, you can reach all early allocated blocks. */
125 basicblock *u_blocks;
126 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 int u_nfblocks;
129 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int u_firstlineno; /* the first lineno of the block */
132 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000133 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 int u_lineno_set; /* boolean to indicate whether instr
135 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136};
137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000143
144Note that we don't track recursion levels during compilation - the
145task of detecting and rejecting excessive levels of nesting is
146handled by the symbol analysis pass.
147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148*/
149
150struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200151 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 struct symtable *c_st;
153 PyFutureFeatures *c_future; /* pointer to module's __future__ */
154 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155
Georg Brandl8334fd92010-12-04 10:26:46 +0000156 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 int c_interactive; /* true if in interactive mode */
158 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 struct compiler_unit *u; /* compiler state for current block */
161 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
162 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163};
164
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100165static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166static void compiler_free(struct compiler *);
167static basicblock *compiler_new_block(struct compiler *);
168static int compiler_next_instr(struct compiler *, basicblock *);
169static int compiler_addop(struct compiler *, int);
170static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100171static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static basicblock *compiler_use_new_block(struct compiler *);
174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
182static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184
185static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189/* Returns true if there is a loop on the fblock stack. */
190static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
192static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000193static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500195static int compiler_with(struct compiler *, stmt_ty, int);
Victor Stinnerad9a0662013-11-19 22:23:20 +0100196static int compiler_call_helper(struct compiler *c, Py_ssize_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 asdl_seq *args,
198 asdl_seq *keywords,
199 expr_ty starargs,
200 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500201static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400202static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Petersonb173f782009-05-05 22:31:58 +0000207#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100389 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
395 k = PyTuple_Pack(2, k, k->ob_type);
396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100417dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100451 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
458 tuple = PyTuple_Pack(2, k, k->ob_type);
459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
479 assert((void *)block != (void *)0xcbcbcbcb);
480 assert((void *)block != (void *)0xfbfbfbfb);
481 assert((void *)block != (void *)0xdbdbdbdb);
482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
527 struct compiler_unit));
528 if (!u) {
529 PyErr_NoMemory();
530 return 0;
531 }
532 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100533 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 u->u_argcount = 0;
535 u->u_kwonlyargcount = 0;
536 u->u_ste = PySymtable_Lookup(c->c_st, key);
537 if (!u->u_ste) {
538 compiler_unit_free(u);
539 return 0;
540 }
541 Py_INCREF(name);
542 u->u_name = name;
543 u->u_varnames = list2dict(u->u_ste->ste_varnames);
544 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
545 if (!u->u_varnames || !u->u_cellvars) {
546 compiler_unit_free(u);
547 return 0;
548 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500549 if (u->u_ste->ste_needs_class_closure) {
550 /* Cook up a implicit __class__ cell. */
551 _Py_IDENTIFIER(__class__);
552 PyObject *tuple, *name, *zero;
553 int res;
554 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
555 assert(PyDict_Size(u->u_cellvars) == 0);
556 name = _PyUnicode_FromId(&PyId___class__);
557 if (!name) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
562 if (!tuple) {
563 compiler_unit_free(u);
564 return 0;
565 }
566 zero = PyLong_FromLong(0);
567 if (!zero) {
568 Py_DECREF(tuple);
569 compiler_unit_free(u);
570 return 0;
571 }
572 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
573 Py_DECREF(tuple);
574 Py_DECREF(zero);
575 if (res < 0) {
576 compiler_unit_free(u);
577 return 0;
578 }
579 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
582 PyDict_Size(u->u_cellvars));
583 if (!u->u_freevars) {
584 compiler_unit_free(u);
585 return 0;
586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_blocks = NULL;
589 u->u_nfblocks = 0;
590 u->u_firstlineno = lineno;
591 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000592 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_lineno_set = 0;
594 u->u_consts = PyDict_New();
595 if (!u->u_consts) {
596 compiler_unit_free(u);
597 return 0;
598 }
599 u->u_names = PyDict_New();
600 if (!u->u_names) {
601 compiler_unit_free(u);
602 return 0;
603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* Push the old compiler_unit on the stack. */
608 if (c->u) {
609 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
610 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
611 Py_XDECREF(capsule);
612 compiler_unit_free(u);
613 return 0;
614 }
615 Py_DECREF(capsule);
616 u->u_private = c->u->u_private;
617 Py_XINCREF(u->u_private);
618 }
619 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 c->c_nestlevel++;
622 if (compiler_use_new_block(c) == NULL)
623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400625 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
626 if (!compiler_set_qualname(c))
627 return 0;
628 }
629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631}
632
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000633static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634compiler_exit_scope(struct compiler *c)
635{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100636 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel--;
640 compiler_unit_free(c->u);
641 /* Restore c->u to the parent unit. */
642 n = PyList_GET_SIZE(c->c_stack) - 1;
643 if (n >= 0) {
644 capsule = PyList_GET_ITEM(c->c_stack, n);
645 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
646 assert(c->u);
647 /* we are deleting from a list so this really shouldn't fail */
648 if (PySequence_DelItem(c->c_stack, n) < 0)
649 Py_FatalError("compiler_exit_scope()");
650 compiler_unit_check(c->u);
651 }
652 else
653 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655}
656
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400657static int
658compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400661 _Py_static_string(dot_locals, ".<locals>");
662 Py_ssize_t stack_size;
663 struct compiler_unit *u = c->u;
664 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400668 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 if (stack_size > 1) {
670 int scope, force_global = 0;
671 struct compiler_unit *parent;
672 PyObject *mangled, *capsule;
673
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400674 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
676 assert(parent);
677
678 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) {
679 assert(u->u_name);
680 mangled = _Py_Mangle(parent->u_private, u->u_name);
681 if (!mangled)
682 return 0;
683 scope = PyST_GetScope(parent->u_ste, mangled);
684 Py_DECREF(mangled);
685 assert(scope != GLOBAL_IMPLICIT);
686 if (scope == GLOBAL_EXPLICIT)
687 force_global = 1;
688 }
689
690 if (!force_global) {
691 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
692 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
693 dot_locals_str = _PyUnicode_FromId(&dot_locals);
694 if (dot_locals_str == NULL)
695 return 0;
696 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
697 if (base == NULL)
698 return 0;
699 }
700 else {
701 Py_INCREF(parent->u_qualname);
702 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400703 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100704 }
705 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400706
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 if (base != NULL) {
708 dot_str = _PyUnicode_FromId(&dot);
709 if (dot_str == NULL) {
710 Py_DECREF(base);
711 return 0;
712 }
713 name = PyUnicode_Concat(base, dot_str);
714 Py_DECREF(base);
715 if (name == NULL)
716 return 0;
717 PyUnicode_Append(&name, u->u_name);
718 if (name == NULL)
719 return 0;
720 }
721 else {
722 Py_INCREF(u->u_name);
723 name = u->u_name;
724 }
725 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100726
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400727 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728}
729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730/* Allocate a new block and return a pointer to it.
731 Returns NULL on error.
732*/
733
734static basicblock *
735compiler_new_block(struct compiler *c)
736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 basicblock *b;
738 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 u = c->u;
741 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
742 if (b == NULL) {
743 PyErr_NoMemory();
744 return NULL;
745 }
746 memset((void *)b, 0, sizeof(basicblock));
747 /* Extend the singly linked list of blocks with new block. */
748 b->b_list = u->u_blocks;
749 u->u_blocks = b;
750 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751}
752
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753static basicblock *
754compiler_use_new_block(struct compiler *c)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 basicblock *block = compiler_new_block(c);
757 if (block == NULL)
758 return NULL;
759 c->u->u_curblock = block;
760 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761}
762
763static basicblock *
764compiler_next_block(struct compiler *c)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 basicblock *block = compiler_new_block(c);
767 if (block == NULL)
768 return NULL;
769 c->u->u_curblock->b_next = block;
770 c->u->u_curblock = block;
771 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772}
773
774static basicblock *
775compiler_use_next_block(struct compiler *c, basicblock *block)
776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 assert(block != NULL);
778 c->u->u_curblock->b_next = block;
779 c->u->u_curblock = block;
780 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781}
782
783/* Returns the offset of the next instruction in the current block's
784 b_instr array. Resizes the b_instr as necessary.
785 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000786*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787
788static int
789compiler_next_instr(struct compiler *c, basicblock *b)
790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 assert(b != NULL);
792 if (b->b_instr == NULL) {
793 b->b_instr = (struct instr *)PyObject_Malloc(
794 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
795 if (b->b_instr == NULL) {
796 PyErr_NoMemory();
797 return -1;
798 }
799 b->b_ialloc = DEFAULT_BLOCK_SIZE;
800 memset((char *)b->b_instr, 0,
801 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
802 }
803 else if (b->b_iused == b->b_ialloc) {
804 struct instr *tmp;
805 size_t oldsize, newsize;
806 oldsize = b->b_ialloc * sizeof(struct instr);
807 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (oldsize > (PY_SIZE_MAX >> 1)) {
810 PyErr_NoMemory();
811 return -1;
812 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (newsize == 0) {
815 PyErr_NoMemory();
816 return -1;
817 }
818 b->b_ialloc <<= 1;
819 tmp = (struct instr *)PyObject_Realloc(
820 (void *)b->b_instr, newsize);
821 if (tmp == NULL) {
822 PyErr_NoMemory();
823 return -1;
824 }
825 b->b_instr = tmp;
826 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
827 }
828 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000829}
830
Christian Heimes2202f872008-02-06 14:31:34 +0000831/* Set the i_lineno member of the instruction at offset off if the
832 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000833 already been set. If it has been set, the call has no effect.
834
Christian Heimes2202f872008-02-06 14:31:34 +0000835 The line number is reset in the following cases:
836 - when entering a new scope
837 - on each statement
838 - on each expression that start a new line
839 - before the "except" clause
840 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000841*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843static void
844compiler_set_lineno(struct compiler *c, int off)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 basicblock *b;
847 if (c->u->u_lineno_set)
848 return;
849 c->u->u_lineno_set = 1;
850 b = c->u->u_curblock;
851 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852}
853
Larry Hastings3a907972013-11-23 14:49:22 -0800854int
855PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 switch (opcode) {
858 case POP_TOP:
859 return -1;
860 case ROT_TWO:
861 case ROT_THREE:
862 return 0;
863 case DUP_TOP:
864 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000865 case DUP_TOP_TWO:
866 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 case UNARY_POSITIVE:
869 case UNARY_NEGATIVE:
870 case UNARY_NOT:
871 case UNARY_INVERT:
872 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 case SET_ADD:
875 case LIST_APPEND:
876 return -1;
877 case MAP_ADD:
878 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case BINARY_POWER:
881 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400882 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 case BINARY_MODULO:
884 case BINARY_ADD:
885 case BINARY_SUBTRACT:
886 case BINARY_SUBSCR:
887 case BINARY_FLOOR_DIVIDE:
888 case BINARY_TRUE_DIVIDE:
889 return -1;
890 case INPLACE_FLOOR_DIVIDE:
891 case INPLACE_TRUE_DIVIDE:
892 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case INPLACE_ADD:
895 case INPLACE_SUBTRACT:
896 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400897 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case INPLACE_MODULO:
899 return -1;
900 case STORE_SUBSCR:
901 return -3;
902 case STORE_MAP:
903 return -2;
904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
932 case WITH_CLEANUP:
933 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case RETURN_VALUE:
935 return -1;
936 case IMPORT_STAR:
937 return -1;
938 case YIELD_VALUE:
939 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500940 case YIELD_FROM:
941 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case POP_BLOCK:
943 return 0;
944 case POP_EXCEPT:
945 return 0; /* -3 except if bad bytecode */
946 case END_FINALLY:
947 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case STORE_NAME:
950 return -1;
951 case DELETE_NAME:
952 return 0;
953 case UNPACK_SEQUENCE:
954 return oparg-1;
955 case UNPACK_EX:
956 return (oparg&0xFF) + (oparg>>8);
957 case FOR_ITER:
958 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case STORE_ATTR:
961 return -2;
962 case DELETE_ATTR:
963 return -1;
964 case STORE_GLOBAL:
965 return -1;
966 case DELETE_GLOBAL:
967 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case LOAD_CONST:
969 return 1;
970 case LOAD_NAME:
971 return 1;
972 case BUILD_TUPLE:
973 case BUILD_LIST:
974 case BUILD_SET:
975 return 1-oparg;
976 case BUILD_MAP:
977 return 1;
978 case LOAD_ATTR:
979 return 0;
980 case COMPARE_OP:
981 return -1;
982 case IMPORT_NAME:
983 return -1;
984 case IMPORT_FROM:
985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case JUMP_FORWARD:
988 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
989 case JUMP_IF_FALSE_OR_POP: /* "" */
990 case JUMP_ABSOLUTE:
991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case POP_JUMP_IF_FALSE:
994 case POP_JUMP_IF_TRUE:
995 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case LOAD_GLOBAL:
998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case CONTINUE_LOOP:
1001 return 0;
1002 case SETUP_LOOP:
1003 return 0;
1004 case SETUP_EXCEPT:
1005 case SETUP_FINALLY:
1006 return 6; /* can push 3 values for the new exception
1007 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_FAST:
1010 return 1;
1011 case STORE_FAST:
1012 return -1;
1013 case DELETE_FAST:
1014 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case RAISE_VARARGS:
1017 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001018#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case CALL_FUNCTION:
1020 return -NARGS(oparg);
1021 case CALL_FUNCTION_VAR:
1022 case CALL_FUNCTION_KW:
1023 return -NARGS(oparg)-1;
1024 case CALL_FUNCTION_VAR_KW:
1025 return -NARGS(oparg)-2;
1026 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001027 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001029 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001030#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case BUILD_SLICE:
1032 if (oparg == 3)
1033 return -2;
1034 else
1035 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case LOAD_CLOSURE:
1038 return 1;
1039 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001040 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return 1;
1042 case STORE_DEREF:
1043 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001044 case DELETE_DEREF:
1045 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001047 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 }
Larry Hastings3a907972013-11-23 14:49:22 -08001049 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050}
1051
1052/* Add an opcode with no argument.
1053 Returns 0 on failure, 1 on success.
1054*/
1055
1056static int
1057compiler_addop(struct compiler *c, int opcode)
1058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 basicblock *b;
1060 struct instr *i;
1061 int off;
1062 off = compiler_next_instr(c, c->u->u_curblock);
1063 if (off < 0)
1064 return 0;
1065 b = c->u->u_curblock;
1066 i = &b->b_instr[off];
1067 i->i_opcode = opcode;
1068 i->i_hasarg = 0;
1069 if (opcode == RETURN_VALUE)
1070 b->b_return = 1;
1071 compiler_set_lineno(c, off);
1072 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
Victor Stinnerf8e32212013-11-19 23:56:34 +01001075static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *t, *v;
1079 Py_ssize_t arg;
1080 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Serhiy Storchaka95949422013-08-27 19:40:23 +03001082 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1084 if (PyFloat_Check(o)) {
1085 d = PyFloat_AS_DOUBLE(o);
1086 /* all we need is to make the tuple different in either the 0.0
1087 * or -0.0 case from all others, just to avoid the "coercion".
1088 */
1089 if (d == 0.0 && copysign(1.0, d) < 0.0)
1090 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1091 else
1092 t = PyTuple_Pack(2, o, o->ob_type);
1093 }
1094 else if (PyComplex_Check(o)) {
1095 Py_complex z;
1096 int real_negzero, imag_negzero;
1097 /* For the complex case we must make complex(x, 0.)
1098 different from complex(x, -0.) and complex(0., y)
1099 different from complex(-0., y), for any x and y.
1100 All four complex zeros must be distinguished.*/
1101 z = PyComplex_AsCComplex(o);
1102 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1103 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1104 if (real_negzero && imag_negzero) {
1105 t = PyTuple_Pack(5, o, o->ob_type,
1106 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001107 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 else if (imag_negzero) {
1109 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 else if (real_negzero) {
1112 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1113 }
1114 else {
1115 t = PyTuple_Pack(2, o, o->ob_type);
1116 }
1117 }
1118 else {
1119 t = PyTuple_Pack(2, o, o->ob_type);
1120 }
1121 if (t == NULL)
1122 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 v = PyDict_GetItem(dict, t);
1125 if (!v) {
1126 if (PyErr_Occurred())
1127 return -1;
1128 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001129 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!v) {
1131 Py_DECREF(t);
1132 return -1;
1133 }
1134 if (PyDict_SetItem(dict, t, v) < 0) {
1135 Py_DECREF(t);
1136 Py_DECREF(v);
1137 return -1;
1138 }
1139 Py_DECREF(v);
1140 }
1141 else
1142 arg = PyLong_AsLong(v);
1143 Py_DECREF(t);
1144 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145}
1146
1147static int
1148compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001151 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return compiler_addop_i(c, opcode, arg);
1155}
1156
1157static int
1158compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1163 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 arg = compiler_add_o(c, dict, mangled);
1166 Py_DECREF(mangled);
1167 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001168 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 return compiler_addop_i(c, opcode, arg);
1170}
1171
1172/* Add an opcode with an integer argument.
1173 Returns 0 on failure, 1 on success.
1174*/
1175
1176static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 struct instr *i;
1180 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181
1182 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1183 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001184 assert((-2147483647-1) <= oparg);
1185 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 off = compiler_next_instr(c, c->u->u_curblock);
1188 if (off < 0)
1189 return 0;
1190 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001191 i->i_opcode = opcode;
1192 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 i->i_hasarg = 1;
1194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 assert(b != NULL);
1205 off = compiler_next_instr(c, c->u->u_curblock);
1206 if (off < 0)
1207 return 0;
1208 i = &c->u->u_curblock->b_instr[off];
1209 i->i_opcode = opcode;
1210 i->i_target = b;
1211 i->i_hasarg = 1;
1212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1221 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 it as the current block. NEXT_BLOCK() also creates an implicit jump
1223 from the current block to the new block.
1224*/
1225
Thomas Wouters89f507f2006-12-13 04:49:30 +00001226/* The returns inside these macros make it impossible to decref objects
1227 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228*/
1229
1230
1231#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (compiler_use_new_block((C)) == NULL) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
1236#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (compiler_next_block((C)) == NULL) \
1238 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239}
1240
1241#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (!compiler_addop((C), (OP))) \
1243 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001246#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (!compiler_addop((C), (OP))) { \
1248 compiler_exit_scope(c); \
1249 return 0; \
1250 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001251}
1252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1255 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256}
1257
1258#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_i((C), (OP), (O))) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_addop_j((C), (OP), (O), 1)) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_addop_j((C), (OP), (O), 0)) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1279 the ASDL name to synthesize the name of the C type and the visit function.
1280*/
1281
1282#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (!compiler_visit_ ## TYPE((C), (V))) \
1284 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285}
1286
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001287#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (!compiler_visit_ ## TYPE((C), (V))) { \
1289 compiler_exit_scope(c); \
1290 return 0; \
1291 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001292}
1293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!compiler_visit_slice((C), (V), (CTX))) \
1296 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
1299#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int _i; \
1301 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1302 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1303 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1304 if (!compiler_visit_ ## TYPE((C), elt)) \
1305 return 0; \
1306 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307}
1308
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001309#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 int _i; \
1311 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1312 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1313 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1314 if (!compiler_visit_ ## TYPE((C), elt)) { \
1315 compiler_exit_scope(c); \
1316 return 0; \
1317 } \
1318 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001319}
1320
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321static int
1322compiler_isdocstring(stmt_ty s)
1323{
1324 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 return s->v.Expr.value->kind == Str_kind;
1327}
1328
1329/* Compile a sequence of statements, checking for a docstring. */
1330
1331static int
1332compiler_body(struct compiler *c, asdl_seq *stmts)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 int i = 0;
1335 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (!asdl_seq_LEN(stmts))
1338 return 1;
1339 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001340 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* don't generate docstrings if -OO */
1342 i = 1;
1343 VISIT(c, expr, st->v.Expr.value);
1344 if (!compiler_nameop(c, __doc__, Store))
1345 return 0;
1346 }
1347 for (; i < asdl_seq_LEN(stmts); i++)
1348 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1349 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350}
1351
1352static PyCodeObject *
1353compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyCodeObject *co;
1356 int addNone = 1;
1357 static PyObject *module;
1358 if (!module) {
1359 module = PyUnicode_InternFromString("<module>");
1360 if (!module)
1361 return NULL;
1362 }
1363 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001364 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 return NULL;
1366 switch (mod->kind) {
1367 case Module_kind:
1368 if (!compiler_body(c, mod->v.Module.body)) {
1369 compiler_exit_scope(c);
1370 return 0;
1371 }
1372 break;
1373 case Interactive_kind:
1374 c->c_interactive = 1;
1375 VISIT_SEQ_IN_SCOPE(c, stmt,
1376 mod->v.Interactive.body);
1377 break;
1378 case Expression_kind:
1379 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1380 addNone = 0;
1381 break;
1382 case Suite_kind:
1383 PyErr_SetString(PyExc_SystemError,
1384 "suite should not be possible");
1385 return 0;
1386 default:
1387 PyErr_Format(PyExc_SystemError,
1388 "module kind %d should not be possible",
1389 mod->kind);
1390 return 0;
1391 }
1392 co = assemble(c, addNone);
1393 compiler_exit_scope(c);
1394 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001395}
1396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397/* The test for LOCAL must come before the test for FREE in order to
1398 handle classes where name is both local and free. The local var is
1399 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001400*/
1401
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402static int
1403get_ref_type(struct compiler *c, PyObject *name)
1404{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001405 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001406 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1407 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1408 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001409 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (scope == 0) {
1411 char buf[350];
1412 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001413 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001415 PyUnicode_AsUTF8(name),
1416 PyUnicode_AsUTF8(c->u->u_name),
1417 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1418 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1419 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1420 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 );
1422 Py_FatalError(buf);
1423 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426}
1427
1428static int
1429compiler_lookup_arg(PyObject *dict, PyObject *name)
1430{
1431 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001434 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001436 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001438 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001439 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001443compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001445 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001446 if (qualname == NULL)
1447 qualname = co->co_name;
1448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (free == 0) {
1450 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001451 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 ADDOP_I(c, MAKE_FUNCTION, args);
1453 return 1;
1454 }
1455 for (i = 0; i < free; ++i) {
1456 /* Bypass com_addop_varname because it will generate
1457 LOAD_DEREF but LOAD_CLOSURE is needed.
1458 */
1459 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1460 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* Special case: If a class contains a method with a
1463 free variable that has the same name as a method,
1464 the name will be considered free *and* local in the
1465 class. It should be handled by the closure, as
1466 well as by the normal name loookup logic.
1467 */
1468 reftype = get_ref_type(c, name);
1469 if (reftype == CELL)
1470 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1471 else /* (reftype == FREE) */
1472 arg = compiler_lookup_arg(c->u->u_freevars, name);
1473 if (arg == -1) {
1474 fprintf(stderr,
1475 "lookup %s in %s %d %d\n"
1476 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001477 PyUnicode_AsUTF8(PyObject_Repr(name)),
1478 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001480 PyUnicode_AsUTF8(co->co_name),
1481 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 Py_FatalError("compiler_make_closure()");
1483 }
1484 ADDOP_I(c, LOAD_CLOSURE, arg);
1485 }
1486 ADDOP_I(c, BUILD_TUPLE, free);
1487 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001488 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 ADDOP_I(c, MAKE_CLOSURE, args);
1490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491}
1492
1493static int
1494compiler_decorators(struct compiler *c, asdl_seq* decos)
1495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!decos)
1499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1502 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1503 }
1504 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
1507static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001508compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 int i, default_count = 0;
1512 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1513 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1514 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1515 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001516 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1517 if (!mangled)
1518 return -1;
1519 ADDOP_O(c, LOAD_CONST, mangled, consts);
1520 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!compiler_visit_expr(c, default_)) {
1522 return -1;
1523 }
1524 default_count++;
1525 }
1526 }
1527 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001528}
1529
1530static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001531compiler_visit_argannotation(struct compiler *c, identifier id,
1532 expr_ty annotation, PyObject *names)
1533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001535 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001537 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001538 if (!mangled)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 return -1;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001540 if (PyList_Append(names, mangled) < 0) {
1541 Py_DECREF(mangled);
1542 return -1;
1543 }
1544 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 }
1546 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001547}
1548
1549static int
1550compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1551 PyObject *names)
1552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 int i, error;
1554 for (i = 0; i < asdl_seq_LEN(args); i++) {
1555 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1556 error = compiler_visit_argannotation(
1557 c,
1558 arg->arg,
1559 arg->annotation,
1560 names);
1561 if (error)
1562 return error;
1563 }
1564 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001565}
1566
1567static int
1568compiler_visit_annotations(struct compiler *c, arguments_ty args,
1569 expr_ty returns)
1570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Push arg annotations and a list of the argument names. Return the #
1572 of items pushed. The expressions are evaluated out-of-order wrt the
1573 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1576 */
1577 static identifier return_str;
1578 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001579 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 names = PyList_New(0);
1581 if (!names)
1582 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 if (compiler_visit_argannotations(c, args->args, names))
1585 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001586 if (args->vararg && args->vararg->annotation &&
1587 compiler_visit_argannotation(c, args->vararg->arg,
1588 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 goto error;
1590 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1591 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001592 if (args->kwarg && args->kwarg->annotation &&
1593 compiler_visit_argannotation(c, args->kwarg->arg,
1594 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (!return_str) {
1598 return_str = PyUnicode_InternFromString("return");
1599 if (!return_str)
1600 goto error;
1601 }
1602 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1603 goto error;
1604 }
1605
1606 len = PyList_GET_SIZE(names);
1607 if (len > 65534) {
1608 /* len must fit in 16 bits, and len is incremented below */
1609 PyErr_SetString(PyExc_SyntaxError,
1610 "too many annotations");
1611 goto error;
1612 }
1613 if (len) {
1614 /* convert names to a tuple and place on stack */
1615 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001616 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *s = PyTuple_New(len);
1618 if (!s)
1619 goto error;
1620 for (i = 0; i < len; i++) {
1621 elt = PyList_GET_ITEM(names, i);
1622 Py_INCREF(elt);
1623 PyTuple_SET_ITEM(s, i, elt);
1624 }
1625 ADDOP_O(c, LOAD_CONST, s, consts);
1626 Py_DECREF(s);
1627 len++; /* include the just-pushed tuple */
1628 }
1629 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001630
1631 /* We just checked that len <= 65535, see above */
1632 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001633
1634error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 Py_DECREF(names);
1636 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001637}
1638
1639static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640compiler_function(struct compiler *c, stmt_ty s)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001643 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 arguments_ty args = s->v.FunctionDef.args;
1645 expr_ty returns = s->v.FunctionDef.returns;
1646 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1647 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001648 Py_ssize_t i, n, arglength;
1649 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (!compiler_decorators(c, decos))
1655 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001656 if (args->defaults)
1657 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (args->kwonlyargs) {
1659 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1660 args->kw_defaults);
1661 if (res < 0)
1662 return 0;
1663 kw_default_count = res;
1664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 num_annotations = compiler_visit_annotations(c, args, returns);
1666 if (num_annotations < 0)
1667 return 0;
1668 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001669
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001670 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1671 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 s->lineno))
1673 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1676 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001677 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 first_const = st->v.Expr.value->v.Str.s;
1679 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1680 compiler_exit_scope(c);
1681 return 0;
1682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 c->u->u_argcount = asdl_seq_LEN(args->args);
1685 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1686 n = asdl_seq_LEN(s->v.FunctionDef.body);
1687 /* if there was a docstring, we need to skip the first statement */
1688 for (i = docstring; i < n; i++) {
1689 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1690 VISIT_IN_SCOPE(c, stmt, st);
1691 }
1692 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001693 qualname = c->u->u_qualname;
1694 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001696 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001697 Py_XDECREF(qualname);
1698 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 arglength = asdl_seq_LEN(args->defaults);
1703 arglength |= kw_default_count << 8;
1704 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001705 compiler_make_closure(c, co, arglength, qualname);
1706 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* decorators */
1710 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1711 ADDOP_I(c, CALL_FUNCTION, 1);
1712 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715}
1716
1717static int
1718compiler_class(struct compiler *c, stmt_ty s)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyCodeObject *co;
1721 PyObject *str;
1722 int i;
1723 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (!compiler_decorators(c, decos))
1726 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* ultimately generate code for:
1729 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1730 where:
1731 <func> is a function/closure created from the class body;
1732 it has a single argument (__locals__) where the dict
1733 (or MutableSequence) representing the locals is passed
1734 <name> is the class name
1735 <bases> is the positional arguments and *varargs argument
1736 <keywords> is the keyword arguments and **kwds argument
1737 This borrows from compiler_call.
1738 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001741 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1742 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 return 0;
1744 /* this block represents what we do in the new scope */
1745 {
1746 /* use the class name for name mangling */
1747 Py_INCREF(s->v.ClassDef.name);
1748 Py_XDECREF(c->u->u_private);
1749 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 /* load (global) __name__ ... */
1751 str = PyUnicode_InternFromString("__name__");
1752 if (!str || !compiler_nameop(c, str, Load)) {
1753 Py_XDECREF(str);
1754 compiler_exit_scope(c);
1755 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001756 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_DECREF(str);
1758 /* ... and store it as __module__ */
1759 str = PyUnicode_InternFromString("__module__");
1760 if (!str || !compiler_nameop(c, str, Store)) {
1761 Py_XDECREF(str);
1762 compiler_exit_scope(c);
1763 return 0;
1764 }
1765 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001766 assert(c->u->u_qualname);
1767 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001768 str = PyUnicode_InternFromString("__qualname__");
1769 if (!str || !compiler_nameop(c, str, Store)) {
1770 Py_XDECREF(str);
1771 compiler_exit_scope(c);
1772 return 0;
1773 }
1774 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* compile the body proper */
1776 if (!compiler_body(c, s->v.ClassDef.body)) {
1777 compiler_exit_scope(c);
1778 return 0;
1779 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001780 if (c->u->u_ste->ste_needs_class_closure) {
1781 /* return the (empty) __class__ cell */
1782 str = PyUnicode_InternFromString("__class__");
1783 if (str == NULL) {
1784 compiler_exit_scope(c);
1785 return 0;
1786 }
1787 i = compiler_lookup_arg(c->u->u_cellvars, str);
1788 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001789 if (i < 0) {
1790 compiler_exit_scope(c);
1791 return 0;
1792 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001793 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* Return the cell where to store __class__ */
1795 ADDOP_I(c, LOAD_CLOSURE, i);
1796 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001797 else {
1798 assert(PyDict_Size(c->u->u_cellvars) == 0);
1799 /* This happens when nobody references the cell. Return None. */
1800 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1803 /* create the code object */
1804 co = assemble(c, 1);
1805 }
1806 /* leave the new scope */
1807 compiler_exit_scope(c);
1808 if (co == NULL)
1809 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 /* 2. load the 'build_class' function */
1812 ADDOP(c, LOAD_BUILD_CLASS);
1813
1814 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001815 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_DECREF(co);
1817
1818 /* 4. load class name */
1819 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1820
1821 /* 5. generate the rest of the code for the call */
1822 if (!compiler_call_helper(c, 2,
1823 s->v.ClassDef.bases,
1824 s->v.ClassDef.keywords,
1825 s->v.ClassDef.starargs,
1826 s->v.ClassDef.kwargs))
1827 return 0;
1828
1829 /* 6. apply decorators */
1830 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1831 ADDOP_I(c, CALL_FUNCTION, 1);
1832 }
1833
1834 /* 7. store into <name> */
1835 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1836 return 0;
1837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838}
1839
1840static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001841compiler_ifexp(struct compiler *c, expr_ty e)
1842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 basicblock *end, *next;
1844
1845 assert(e->kind == IfExp_kind);
1846 end = compiler_new_block(c);
1847 if (end == NULL)
1848 return 0;
1849 next = compiler_new_block(c);
1850 if (next == NULL)
1851 return 0;
1852 VISIT(c, expr, e->v.IfExp.test);
1853 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1854 VISIT(c, expr, e->v.IfExp.body);
1855 ADDOP_JREL(c, JUMP_FORWARD, end);
1856 compiler_use_next_block(c, next);
1857 VISIT(c, expr, e->v.IfExp.orelse);
1858 compiler_use_next_block(c, end);
1859 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001860}
1861
1862static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863compiler_lambda(struct compiler *c, expr_ty e)
1864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001866 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001868 int kw_default_count = 0;
1869 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 arguments_ty args = e->v.Lambda.args;
1871 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (!name) {
1874 name = PyUnicode_InternFromString("<lambda>");
1875 if (!name)
1876 return 0;
1877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001879 if (args->defaults)
1880 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (args->kwonlyargs) {
1882 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1883 args->kw_defaults);
1884 if (res < 0) return 0;
1885 kw_default_count = res;
1886 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001887 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001888 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Make None the first constant, so the lambda can't have a
1892 docstring. */
1893 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 c->u->u_argcount = asdl_seq_LEN(args->args);
1897 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1898 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1899 if (c->u->u_ste->ste_generator) {
1900 ADDOP_IN_SCOPE(c, POP_TOP);
1901 }
1902 else {
1903 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1904 }
1905 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001906 qualname = c->u->u_qualname;
1907 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001909 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 arglength = asdl_seq_LEN(args->defaults);
1913 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001914 compiler_make_closure(c, co, arglength, qualname);
1915 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 Py_DECREF(co);
1917
1918 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922compiler_if(struct compiler *c, stmt_ty s)
1923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 basicblock *end, *next;
1925 int constant;
1926 assert(s->kind == If_kind);
1927 end = compiler_new_block(c);
1928 if (end == NULL)
1929 return 0;
1930
Georg Brandl8334fd92010-12-04 10:26:46 +00001931 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 /* constant = 0: "if 0"
1933 * constant = 1: "if 1", "if 2", ...
1934 * constant = -1: rest */
1935 if (constant == 0) {
1936 if (s->v.If.orelse)
1937 VISIT_SEQ(c, stmt, s->v.If.orelse);
1938 } else if (constant == 1) {
1939 VISIT_SEQ(c, stmt, s->v.If.body);
1940 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001941 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 next = compiler_new_block(c);
1943 if (next == NULL)
1944 return 0;
1945 }
1946 else
1947 next = end;
1948 VISIT(c, expr, s->v.If.test);
1949 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1950 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001951 if (asdl_seq_LEN(s->v.If.orelse)) {
1952 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 compiler_use_next_block(c, next);
1954 VISIT_SEQ(c, stmt, s->v.If.orelse);
1955 }
1956 }
1957 compiler_use_next_block(c, end);
1958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959}
1960
1961static int
1962compiler_for(struct compiler *c, stmt_ty s)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 start = compiler_new_block(c);
1967 cleanup = compiler_new_block(c);
1968 end = compiler_new_block(c);
1969 if (start == NULL || end == NULL || cleanup == NULL)
1970 return 0;
1971 ADDOP_JREL(c, SETUP_LOOP, end);
1972 if (!compiler_push_fblock(c, LOOP, start))
1973 return 0;
1974 VISIT(c, expr, s->v.For.iter);
1975 ADDOP(c, GET_ITER);
1976 compiler_use_next_block(c, start);
1977 ADDOP_JREL(c, FOR_ITER, cleanup);
1978 VISIT(c, expr, s->v.For.target);
1979 VISIT_SEQ(c, stmt, s->v.For.body);
1980 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1981 compiler_use_next_block(c, cleanup);
1982 ADDOP(c, POP_BLOCK);
1983 compiler_pop_fblock(c, LOOP, start);
1984 VISIT_SEQ(c, stmt, s->v.For.orelse);
1985 compiler_use_next_block(c, end);
1986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987}
1988
1989static int
1990compiler_while(struct compiler *c, stmt_ty s)
1991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001993 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (constant == 0) {
1996 if (s->v.While.orelse)
1997 VISIT_SEQ(c, stmt, s->v.While.orelse);
1998 return 1;
1999 }
2000 loop = compiler_new_block(c);
2001 end = compiler_new_block(c);
2002 if (constant == -1) {
2003 anchor = compiler_new_block(c);
2004 if (anchor == NULL)
2005 return 0;
2006 }
2007 if (loop == NULL || end == NULL)
2008 return 0;
2009 if (s->v.While.orelse) {
2010 orelse = compiler_new_block(c);
2011 if (orelse == NULL)
2012 return 0;
2013 }
2014 else
2015 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 ADDOP_JREL(c, SETUP_LOOP, end);
2018 compiler_use_next_block(c, loop);
2019 if (!compiler_push_fblock(c, LOOP, loop))
2020 return 0;
2021 if (constant == -1) {
2022 VISIT(c, expr, s->v.While.test);
2023 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2024 }
2025 VISIT_SEQ(c, stmt, s->v.While.body);
2026 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* XXX should the two POP instructions be in a separate block
2029 if there is no else clause ?
2030 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (constant == -1) {
2033 compiler_use_next_block(c, anchor);
2034 ADDOP(c, POP_BLOCK);
2035 }
2036 compiler_pop_fblock(c, LOOP, loop);
2037 if (orelse != NULL) /* what if orelse is just pass? */
2038 VISIT_SEQ(c, stmt, s->v.While.orelse);
2039 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042}
2043
2044static int
2045compiler_continue(struct compiler *c)
2046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2048 static const char IN_FINALLY_ERROR_MSG[] =
2049 "'continue' not supported inside 'finally' clause";
2050 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (!c->u->u_nfblocks)
2053 return compiler_error(c, LOOP_ERROR_MSG);
2054 i = c->u->u_nfblocks - 1;
2055 switch (c->u->u_fblock[i].fb_type) {
2056 case LOOP:
2057 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2058 break;
2059 case EXCEPT:
2060 case FINALLY_TRY:
2061 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2062 /* Prevent continue anywhere under a finally
2063 even if hidden in a sub-try or except. */
2064 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2065 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2066 }
2067 if (i == -1)
2068 return compiler_error(c, LOOP_ERROR_MSG);
2069 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2070 break;
2071 case FINALLY_END:
2072 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076}
2077
2078/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079
2080 SETUP_FINALLY L
2081 <code for body>
2082 POP_BLOCK
2083 LOAD_CONST <None>
2084 L: <code for finalbody>
2085 END_FINALLY
2086
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 The special instructions use the block stack. Each block
2088 stack entry contains the instruction that created it (here
2089 SETUP_FINALLY), the level of the value stack at the time the
2090 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 Pushes the current value stack level and the label
2094 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 Pops en entry from the block stack, and pops the value
2097 stack until its level is the same as indicated on the
2098 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 Pops a variable number of entries from the *value* stack
2101 and re-raises the exception they specify. The number of
2102 entries popped depends on the (pseudo) exception type.
2103
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 The block stack is unwound when an exception is raised:
2105 when a SETUP_FINALLY entry is found, the exception is pushed
2106 onto the value stack (and the exception condition is cleared),
2107 and the interpreter jumps to the label gotten from the block
2108 stack.
2109*/
2110
2111static int
2112compiler_try_finally(struct compiler *c, stmt_ty s)
2113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 basicblock *body, *end;
2115 body = compiler_new_block(c);
2116 end = compiler_new_block(c);
2117 if (body == NULL || end == NULL)
2118 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 ADDOP_JREL(c, SETUP_FINALLY, end);
2121 compiler_use_next_block(c, body);
2122 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2123 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002124 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2125 if (!compiler_try_except(c, s))
2126 return 0;
2127 }
2128 else {
2129 VISIT_SEQ(c, stmt, s->v.Try.body);
2130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 ADDOP(c, POP_BLOCK);
2132 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2135 compiler_use_next_block(c, end);
2136 if (!compiler_push_fblock(c, FINALLY_END, end))
2137 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002138 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 ADDOP(c, END_FINALLY);
2140 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143}
2144
2145/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002146 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 (The contents of the value stack is shown in [], with the top
2148 at the right; 'tb' is trace-back info, 'val' the exception's
2149 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150
2151 Value stack Label Instruction Argument
2152 [] SETUP_EXCEPT L1
2153 [] <code for S>
2154 [] POP_BLOCK
2155 [] JUMP_FORWARD L0
2156
2157 [tb, val, exc] L1: DUP )
2158 [tb, val, exc, exc] <evaluate E1> )
2159 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2160 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2161 [tb, val, exc] POP
2162 [tb, val] <assign to V1> (or POP if no V1)
2163 [tb] POP
2164 [] <code for S1>
2165 JUMP_FORWARD L0
2166
2167 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 .............................etc.......................
2169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2171
2172 [] L0: <next statement>
2173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174 Of course, parts are not generated if Vi or Ei is not present.
2175*/
2176static int
2177compiler_try_except(struct compiler *c, stmt_ty s)
2178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002180 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 body = compiler_new_block(c);
2183 except = compiler_new_block(c);
2184 orelse = compiler_new_block(c);
2185 end = compiler_new_block(c);
2186 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2187 return 0;
2188 ADDOP_JREL(c, SETUP_EXCEPT, except);
2189 compiler_use_next_block(c, body);
2190 if (!compiler_push_fblock(c, EXCEPT, body))
2191 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002192 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 ADDOP(c, POP_BLOCK);
2194 compiler_pop_fblock(c, EXCEPT, body);
2195 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002196 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 compiler_use_next_block(c, except);
2198 for (i = 0; i < n; i++) {
2199 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002200 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (!handler->v.ExceptHandler.type && i < n-1)
2202 return compiler_error(c, "default 'except:' must be last");
2203 c->u->u_lineno_set = 0;
2204 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002205 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 except = compiler_new_block(c);
2207 if (except == NULL)
2208 return 0;
2209 if (handler->v.ExceptHandler.type) {
2210 ADDOP(c, DUP_TOP);
2211 VISIT(c, expr, handler->v.ExceptHandler.type);
2212 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2213 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2214 }
2215 ADDOP(c, POP_TOP);
2216 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002217 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002218
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002219 cleanup_end = compiler_new_block(c);
2220 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002221 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002222 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002223
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002224 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2225 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002227 /*
2228 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002229 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002230 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002231 try:
2232 # body
2233 finally:
2234 name = None
2235 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002236 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002238 /* second try: */
2239 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2240 compiler_use_next_block(c, cleanup_body);
2241 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2242 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002244 /* second # body */
2245 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2246 ADDOP(c, POP_BLOCK);
2247 ADDOP(c, POP_EXCEPT);
2248 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002250 /* finally: */
2251 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2252 compiler_use_next_block(c, cleanup_end);
2253 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2254 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002256 /* name = None */
2257 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2258 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002260 /* del name */
2261 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002263 ADDOP(c, END_FINALLY);
2264 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 }
2266 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002267 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002269 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002270 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002271 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272
Guido van Rossumb940e112007-01-10 16:19:56 +00002273 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002274 ADDOP(c, POP_TOP);
2275 compiler_use_next_block(c, cleanup_body);
2276 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2277 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002279 ADDOP(c, POP_EXCEPT);
2280 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 }
2282 ADDOP_JREL(c, JUMP_FORWARD, end);
2283 compiler_use_next_block(c, except);
2284 }
2285 ADDOP(c, END_FINALLY);
2286 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002287 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 compiler_use_next_block(c, end);
2289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290}
2291
2292static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002293compiler_try(struct compiler *c, stmt_ty s) {
2294 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2295 return compiler_try_finally(c, s);
2296 else
2297 return compiler_try_except(c, s);
2298}
2299
2300
2301static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302compiler_import_as(struct compiler *c, identifier name, identifier asname)
2303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* The IMPORT_NAME opcode was already generated. This function
2305 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 If there is a dot in name, we need to split it and emit a
2308 LOAD_ATTR for each name.
2309 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2311 PyUnicode_GET_LENGTH(name), 1);
2312 if (dot == -2)
2313 return -1;
2314 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 Py_ssize_t pos = dot + 1;
2317 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002319 dot = PyUnicode_FindChar(name, '.', pos,
2320 PyUnicode_GET_LENGTH(name), 1);
2321 if (dot == -2)
2322 return -1;
2323 attr = PyUnicode_Substring(name, pos,
2324 (dot != -1) ? dot :
2325 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (!attr)
2327 return -1;
2328 ADDOP_O(c, LOAD_ATTR, attr, names);
2329 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002330 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 }
2332 }
2333 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334}
2335
2336static int
2337compiler_import(struct compiler *c, stmt_ty s)
2338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 /* The Import node stores a module name like a.b.c as a single
2340 string. This is convenient for all cases except
2341 import a.b.c as d
2342 where we need to parse that string to extract the individual
2343 module names.
2344 XXX Perhaps change the representation to make this case simpler?
2345 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002346 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 for (i = 0; i < n; i++) {
2349 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2350 int r;
2351 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 level = PyLong_FromLong(0);
2354 if (level == NULL)
2355 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 ADDOP_O(c, LOAD_CONST, level, consts);
2358 Py_DECREF(level);
2359 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2360 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (alias->asname) {
2363 r = compiler_import_as(c, alias->name, alias->asname);
2364 if (!r)
2365 return r;
2366 }
2367 else {
2368 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002369 Py_ssize_t dot = PyUnicode_FindChar(
2370 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002371 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002373 if (tmp == NULL)
2374 return 0;
2375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002377 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_DECREF(tmp);
2379 }
2380 if (!r)
2381 return r;
2382 }
2383 }
2384 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385}
2386
2387static int
2388compiler_from_import(struct compiler *c, stmt_ty s)
2389{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002390 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 PyObject *names = PyTuple_New(n);
2393 PyObject *level;
2394 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 if (!empty_string) {
2397 empty_string = PyUnicode_FromString("");
2398 if (!empty_string)
2399 return 0;
2400 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 if (!names)
2403 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 level = PyLong_FromLong(s->v.ImportFrom.level);
2406 if (!level) {
2407 Py_DECREF(names);
2408 return 0;
2409 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* build up the names */
2412 for (i = 0; i < n; i++) {
2413 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2414 Py_INCREF(alias->name);
2415 PyTuple_SET_ITEM(names, i, alias->name);
2416 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2419 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2420 Py_DECREF(level);
2421 Py_DECREF(names);
2422 return compiler_error(c, "from __future__ imports must occur "
2423 "at the beginning of the file");
2424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 ADDOP_O(c, LOAD_CONST, level, consts);
2427 Py_DECREF(level);
2428 ADDOP_O(c, LOAD_CONST, names, consts);
2429 Py_DECREF(names);
2430 if (s->v.ImportFrom.module) {
2431 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2432 }
2433 else {
2434 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2435 }
2436 for (i = 0; i < n; i++) {
2437 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2438 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002440 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 assert(n == 1);
2442 ADDOP(c, IMPORT_STAR);
2443 return 1;
2444 }
2445
2446 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2447 store_name = alias->name;
2448 if (alias->asname)
2449 store_name = alias->asname;
2450
2451 if (!compiler_nameop(c, store_name, Store)) {
2452 Py_DECREF(names);
2453 return 0;
2454 }
2455 }
2456 /* remove imported module */
2457 ADDOP(c, POP_TOP);
2458 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459}
2460
2461static int
2462compiler_assert(struct compiler *c, stmt_ty s)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 static PyObject *assertion_error = NULL;
2465 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002466 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467
Georg Brandl8334fd92010-12-04 10:26:46 +00002468 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 return 1;
2470 if (assertion_error == NULL) {
2471 assertion_error = PyUnicode_InternFromString("AssertionError");
2472 if (assertion_error == NULL)
2473 return 0;
2474 }
2475 if (s->v.Assert.test->kind == Tuple_kind &&
2476 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002477 msg = PyUnicode_FromString("assertion is always true, "
2478 "perhaps remove parentheses?");
2479 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002481 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2482 c->c_filename, c->u->u_lineno,
2483 NULL, NULL) == -1) {
2484 Py_DECREF(msg);
2485 return 0;
2486 }
2487 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 }
2489 VISIT(c, expr, s->v.Assert.test);
2490 end = compiler_new_block(c);
2491 if (end == NULL)
2492 return 0;
2493 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2494 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2495 if (s->v.Assert.msg) {
2496 VISIT(c, expr, s->v.Assert.msg);
2497 ADDOP_I(c, CALL_FUNCTION, 1);
2498 }
2499 ADDOP_I(c, RAISE_VARARGS, 1);
2500 compiler_use_next_block(c, end);
2501 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502}
2503
2504static int
2505compiler_visit_stmt(struct compiler *c, stmt_ty s)
2506{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002507 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 /* Always assign a lineno to the next instruction for a stmt. */
2510 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002511 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 switch (s->kind) {
2515 case FunctionDef_kind:
2516 return compiler_function(c, s);
2517 case ClassDef_kind:
2518 return compiler_class(c, s);
2519 case Return_kind:
2520 if (c->u->u_ste->ste_type != FunctionBlock)
2521 return compiler_error(c, "'return' outside function");
2522 if (s->v.Return.value) {
2523 VISIT(c, expr, s->v.Return.value);
2524 }
2525 else
2526 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2527 ADDOP(c, RETURN_VALUE);
2528 break;
2529 case Delete_kind:
2530 VISIT_SEQ(c, expr, s->v.Delete.targets)
2531 break;
2532 case Assign_kind:
2533 n = asdl_seq_LEN(s->v.Assign.targets);
2534 VISIT(c, expr, s->v.Assign.value);
2535 for (i = 0; i < n; i++) {
2536 if (i < n - 1)
2537 ADDOP(c, DUP_TOP);
2538 VISIT(c, expr,
2539 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2540 }
2541 break;
2542 case AugAssign_kind:
2543 return compiler_augassign(c, s);
2544 case For_kind:
2545 return compiler_for(c, s);
2546 case While_kind:
2547 return compiler_while(c, s);
2548 case If_kind:
2549 return compiler_if(c, s);
2550 case Raise_kind:
2551 n = 0;
2552 if (s->v.Raise.exc) {
2553 VISIT(c, expr, s->v.Raise.exc);
2554 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002555 if (s->v.Raise.cause) {
2556 VISIT(c, expr, s->v.Raise.cause);
2557 n++;
2558 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002560 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002562 case Try_kind:
2563 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 case Assert_kind:
2565 return compiler_assert(c, s);
2566 case Import_kind:
2567 return compiler_import(c, s);
2568 case ImportFrom_kind:
2569 return compiler_from_import(c, s);
2570 case Global_kind:
2571 case Nonlocal_kind:
2572 break;
2573 case Expr_kind:
2574 if (c->c_interactive && c->c_nestlevel <= 1) {
2575 VISIT(c, expr, s->v.Expr.value);
2576 ADDOP(c, PRINT_EXPR);
2577 }
2578 else if (s->v.Expr.value->kind != Str_kind &&
2579 s->v.Expr.value->kind != Num_kind) {
2580 VISIT(c, expr, s->v.Expr.value);
2581 ADDOP(c, POP_TOP);
2582 }
2583 break;
2584 case Pass_kind:
2585 break;
2586 case Break_kind:
2587 if (!compiler_in_loop(c))
2588 return compiler_error(c, "'break' outside loop");
2589 ADDOP(c, BREAK_LOOP);
2590 break;
2591 case Continue_kind:
2592 return compiler_continue(c);
2593 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002594 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 }
2596 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597}
2598
2599static int
2600unaryop(unaryop_ty op)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 switch (op) {
2603 case Invert:
2604 return UNARY_INVERT;
2605 case Not:
2606 return UNARY_NOT;
2607 case UAdd:
2608 return UNARY_POSITIVE;
2609 case USub:
2610 return UNARY_NEGATIVE;
2611 default:
2612 PyErr_Format(PyExc_SystemError,
2613 "unary op %d should not be possible", op);
2614 return 0;
2615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616}
2617
2618static int
2619binop(struct compiler *c, operator_ty op)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 switch (op) {
2622 case Add:
2623 return BINARY_ADD;
2624 case Sub:
2625 return BINARY_SUBTRACT;
2626 case Mult:
2627 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002628 case MatMult:
2629 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 case Div:
2631 return BINARY_TRUE_DIVIDE;
2632 case Mod:
2633 return BINARY_MODULO;
2634 case Pow:
2635 return BINARY_POWER;
2636 case LShift:
2637 return BINARY_LSHIFT;
2638 case RShift:
2639 return BINARY_RSHIFT;
2640 case BitOr:
2641 return BINARY_OR;
2642 case BitXor:
2643 return BINARY_XOR;
2644 case BitAnd:
2645 return BINARY_AND;
2646 case FloorDiv:
2647 return BINARY_FLOOR_DIVIDE;
2648 default:
2649 PyErr_Format(PyExc_SystemError,
2650 "binary op %d should not be possible", op);
2651 return 0;
2652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653}
2654
2655static int
2656cmpop(cmpop_ty op)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 switch (op) {
2659 case Eq:
2660 return PyCmp_EQ;
2661 case NotEq:
2662 return PyCmp_NE;
2663 case Lt:
2664 return PyCmp_LT;
2665 case LtE:
2666 return PyCmp_LE;
2667 case Gt:
2668 return PyCmp_GT;
2669 case GtE:
2670 return PyCmp_GE;
2671 case Is:
2672 return PyCmp_IS;
2673 case IsNot:
2674 return PyCmp_IS_NOT;
2675 case In:
2676 return PyCmp_IN;
2677 case NotIn:
2678 return PyCmp_NOT_IN;
2679 default:
2680 return PyCmp_BAD;
2681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682}
2683
2684static int
2685inplace_binop(struct compiler *c, operator_ty op)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 switch (op) {
2688 case Add:
2689 return INPLACE_ADD;
2690 case Sub:
2691 return INPLACE_SUBTRACT;
2692 case Mult:
2693 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002694 case MatMult:
2695 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 case Div:
2697 return INPLACE_TRUE_DIVIDE;
2698 case Mod:
2699 return INPLACE_MODULO;
2700 case Pow:
2701 return INPLACE_POWER;
2702 case LShift:
2703 return INPLACE_LSHIFT;
2704 case RShift:
2705 return INPLACE_RSHIFT;
2706 case BitOr:
2707 return INPLACE_OR;
2708 case BitXor:
2709 return INPLACE_XOR;
2710 case BitAnd:
2711 return INPLACE_AND;
2712 case FloorDiv:
2713 return INPLACE_FLOOR_DIVIDE;
2714 default:
2715 PyErr_Format(PyExc_SystemError,
2716 "inplace binary op %d should not be possible", op);
2717 return 0;
2718 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719}
2720
2721static int
2722compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2723{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002724 int op, scope;
2725 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyObject *dict = c->u->u_names;
2729 PyObject *mangled;
2730 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 mangled = _Py_Mangle(c->u->u_private, name);
2733 if (!mangled)
2734 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002735
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002736 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2737 PyUnicode_CompareWithASCIIString(name, "True") &&
2738 PyUnicode_CompareWithASCIIString(name, "False"));
2739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 op = 0;
2741 optype = OP_NAME;
2742 scope = PyST_GetScope(c->u->u_ste, mangled);
2743 switch (scope) {
2744 case FREE:
2745 dict = c->u->u_freevars;
2746 optype = OP_DEREF;
2747 break;
2748 case CELL:
2749 dict = c->u->u_cellvars;
2750 optype = OP_DEREF;
2751 break;
2752 case LOCAL:
2753 if (c->u->u_ste->ste_type == FunctionBlock)
2754 optype = OP_FAST;
2755 break;
2756 case GLOBAL_IMPLICIT:
2757 if (c->u->u_ste->ste_type == FunctionBlock &&
2758 !c->u->u_ste->ste_unoptimized)
2759 optype = OP_GLOBAL;
2760 break;
2761 case GLOBAL_EXPLICIT:
2762 optype = OP_GLOBAL;
2763 break;
2764 default:
2765 /* scope can be 0 */
2766 break;
2767 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 switch (optype) {
2773 case OP_DEREF:
2774 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002775 case Load:
2776 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2777 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 case Store: op = STORE_DEREF; break;
2779 case AugLoad:
2780 case AugStore:
2781 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002782 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 case Param:
2784 default:
2785 PyErr_SetString(PyExc_SystemError,
2786 "param invalid for deref variable");
2787 return 0;
2788 }
2789 break;
2790 case OP_FAST:
2791 switch (ctx) {
2792 case Load: op = LOAD_FAST; break;
2793 case Store: op = STORE_FAST; break;
2794 case Del: op = DELETE_FAST; break;
2795 case AugLoad:
2796 case AugStore:
2797 break;
2798 case Param:
2799 default:
2800 PyErr_SetString(PyExc_SystemError,
2801 "param invalid for local variable");
2802 return 0;
2803 }
2804 ADDOP_O(c, op, mangled, varnames);
2805 Py_DECREF(mangled);
2806 return 1;
2807 case OP_GLOBAL:
2808 switch (ctx) {
2809 case Load: op = LOAD_GLOBAL; break;
2810 case Store: op = STORE_GLOBAL; break;
2811 case Del: op = DELETE_GLOBAL; break;
2812 case AugLoad:
2813 case AugStore:
2814 break;
2815 case Param:
2816 default:
2817 PyErr_SetString(PyExc_SystemError,
2818 "param invalid for global variable");
2819 return 0;
2820 }
2821 break;
2822 case OP_NAME:
2823 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002824 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 case Store: op = STORE_NAME; break;
2826 case Del: op = DELETE_NAME; break;
2827 case AugLoad:
2828 case AugStore:
2829 break;
2830 case Param:
2831 default:
2832 PyErr_SetString(PyExc_SystemError,
2833 "param invalid for name variable");
2834 return 0;
2835 }
2836 break;
2837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 assert(op);
2840 arg = compiler_add_o(c, dict, mangled);
2841 Py_DECREF(mangled);
2842 if (arg < 0)
2843 return 0;
2844 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845}
2846
2847static int
2848compiler_boolop(struct compiler *c, expr_ty e)
2849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002851 int jumpi;
2852 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 assert(e->kind == BoolOp_kind);
2856 if (e->v.BoolOp.op == And)
2857 jumpi = JUMP_IF_FALSE_OR_POP;
2858 else
2859 jumpi = JUMP_IF_TRUE_OR_POP;
2860 end = compiler_new_block(c);
2861 if (end == NULL)
2862 return 0;
2863 s = e->v.BoolOp.values;
2864 n = asdl_seq_LEN(s) - 1;
2865 assert(n >= 0);
2866 for (i = 0; i < n; ++i) {
2867 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2868 ADDOP_JABS(c, jumpi, end);
2869 }
2870 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2871 compiler_use_next_block(c, end);
2872 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873}
2874
2875static int
2876compiler_list(struct compiler *c, expr_ty e)
2877{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002878 Py_ssize_t n = asdl_seq_LEN(e->v.List.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 if (e->v.List.ctx == Store) {
2880 int i, seen_star = 0;
2881 for (i = 0; i < n; i++) {
2882 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2883 if (elt->kind == Starred_kind && !seen_star) {
2884 if ((i >= (1 << 8)) ||
2885 (n-i-1 >= (INT_MAX >> 8)))
2886 return compiler_error(c,
2887 "too many expressions in "
2888 "star-unpacking assignment");
2889 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2890 seen_star = 1;
2891 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2892 } else if (elt->kind == Starred_kind) {
2893 return compiler_error(c,
2894 "two starred expressions in assignment");
2895 }
2896 }
2897 if (!seen_star) {
2898 ADDOP_I(c, UNPACK_SEQUENCE, n);
2899 }
2900 }
2901 VISIT_SEQ(c, expr, e->v.List.elts);
2902 if (e->v.List.ctx == Load) {
2903 ADDOP_I(c, BUILD_LIST, n);
2904 }
2905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906}
2907
2908static int
2909compiler_tuple(struct compiler *c, expr_ty e)
2910{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002911 Py_ssize_t n = asdl_seq_LEN(e->v.Tuple.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 if (e->v.Tuple.ctx == Store) {
2913 int i, seen_star = 0;
2914 for (i = 0; i < n; i++) {
2915 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2916 if (elt->kind == Starred_kind && !seen_star) {
2917 if ((i >= (1 << 8)) ||
2918 (n-i-1 >= (INT_MAX >> 8)))
2919 return compiler_error(c,
2920 "too many expressions in "
2921 "star-unpacking assignment");
2922 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2923 seen_star = 1;
2924 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2925 } else if (elt->kind == Starred_kind) {
2926 return compiler_error(c,
2927 "two starred expressions in assignment");
2928 }
2929 }
2930 if (!seen_star) {
2931 ADDOP_I(c, UNPACK_SEQUENCE, n);
2932 }
2933 }
2934 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2935 if (e->v.Tuple.ctx == Load) {
2936 ADDOP_I(c, BUILD_TUPLE, n);
2937 }
2938 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939}
2940
2941static int
2942compiler_compare(struct compiler *c, expr_ty e)
2943{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002944 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2948 VISIT(c, expr, e->v.Compare.left);
2949 n = asdl_seq_LEN(e->v.Compare.ops);
2950 assert(n > 0);
2951 if (n > 1) {
2952 cleanup = compiler_new_block(c);
2953 if (cleanup == NULL)
2954 return 0;
2955 VISIT(c, expr,
2956 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2957 }
2958 for (i = 1; i < n; i++) {
2959 ADDOP(c, DUP_TOP);
2960 ADDOP(c, ROT_THREE);
2961 ADDOP_I(c, COMPARE_OP,
2962 cmpop((cmpop_ty)(asdl_seq_GET(
2963 e->v.Compare.ops, i - 1))));
2964 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2965 NEXT_BLOCK(c);
2966 if (i < (n - 1))
2967 VISIT(c, expr,
2968 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2969 }
2970 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2971 ADDOP_I(c, COMPARE_OP,
2972 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2973 if (n > 1) {
2974 basicblock *end = compiler_new_block(c);
2975 if (end == NULL)
2976 return 0;
2977 ADDOP_JREL(c, JUMP_FORWARD, end);
2978 compiler_use_next_block(c, cleanup);
2979 ADDOP(c, ROT_TWO);
2980 ADDOP(c, POP_TOP);
2981 compiler_use_next_block(c, end);
2982 }
2983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984}
2985
2986static int
2987compiler_call(struct compiler *c, expr_ty e)
2988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 VISIT(c, expr, e->v.Call.func);
2990 return compiler_call_helper(c, 0,
2991 e->v.Call.args,
2992 e->v.Call.keywords,
2993 e->v.Call.starargs,
2994 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002995}
2996
2997/* shared code between compiler_call and compiler_class */
2998static int
2999compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003000 Py_ssize_t n, /* Args already pushed */
3001 asdl_seq *args,
3002 asdl_seq *keywords,
3003 expr_ty starargs,
3004 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 n += asdl_seq_LEN(args);
3009 VISIT_SEQ(c, expr, args);
3010 if (keywords) {
3011 VISIT_SEQ(c, keyword, keywords);
3012 n |= asdl_seq_LEN(keywords) << 8;
3013 }
3014 if (starargs) {
3015 VISIT(c, expr, starargs);
3016 code |= 1;
3017 }
3018 if (kwargs) {
3019 VISIT(c, expr, kwargs);
3020 code |= 2;
3021 }
3022 switch (code) {
3023 case 0:
3024 ADDOP_I(c, CALL_FUNCTION, n);
3025 break;
3026 case 1:
3027 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3028 break;
3029 case 2:
3030 ADDOP_I(c, CALL_FUNCTION_KW, n);
3031 break;
3032 case 3:
3033 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3034 break;
3035 }
3036 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037}
3038
Nick Coghlan650f0d02007-04-15 12:05:43 +00003039
3040/* List and set comprehensions and generator expressions work by creating a
3041 nested function to perform the actual iteration. This means that the
3042 iteration variables don't leak into the current scope.
3043 The defined function is called immediately following its definition, with the
3044 result of that call being the result of the expression.
3045 The LC/SC version returns the populated container, while the GE version is
3046 flagged in symtable.c as a generator, so it returns the generator object
3047 when the function is called.
3048 This code *knows* that the loop cannot contain break, continue, or return,
3049 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3050
3051 Possible cleanups:
3052 - iterate over the generator sequence instead of using recursion
3053*/
3054
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056compiler_comprehension_generator(struct compiler *c,
3057 asdl_seq *generators, int gen_index,
3058 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* generate code for the iterator, then each of the ifs,
3061 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 comprehension_ty gen;
3064 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003065 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 start = compiler_new_block(c);
3068 skip = compiler_new_block(c);
3069 if_cleanup = compiler_new_block(c);
3070 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3073 anchor == NULL)
3074 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 if (gen_index == 0) {
3079 /* Receive outermost iter as an implicit argument */
3080 c->u->u_argcount = 1;
3081 ADDOP_I(c, LOAD_FAST, 0);
3082 }
3083 else {
3084 /* Sub-iter - calculate on the fly */
3085 VISIT(c, expr, gen->iter);
3086 ADDOP(c, GET_ITER);
3087 }
3088 compiler_use_next_block(c, start);
3089 ADDOP_JREL(c, FOR_ITER, anchor);
3090 NEXT_BLOCK(c);
3091 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 /* XXX this needs to be cleaned up...a lot! */
3094 n = asdl_seq_LEN(gen->ifs);
3095 for (i = 0; i < n; i++) {
3096 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3097 VISIT(c, expr, e);
3098 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3099 NEXT_BLOCK(c);
3100 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 if (++gen_index < asdl_seq_LEN(generators))
3103 if (!compiler_comprehension_generator(c,
3104 generators, gen_index,
3105 elt, val, type))
3106 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 /* only append after the last for generator */
3109 if (gen_index >= asdl_seq_LEN(generators)) {
3110 /* comprehension specific code */
3111 switch (type) {
3112 case COMP_GENEXP:
3113 VISIT(c, expr, elt);
3114 ADDOP(c, YIELD_VALUE);
3115 ADDOP(c, POP_TOP);
3116 break;
3117 case COMP_LISTCOMP:
3118 VISIT(c, expr, elt);
3119 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3120 break;
3121 case COMP_SETCOMP:
3122 VISIT(c, expr, elt);
3123 ADDOP_I(c, SET_ADD, gen_index + 1);
3124 break;
3125 case COMP_DICTCOMP:
3126 /* With 'd[k] = v', v is evaluated before k, so we do
3127 the same. */
3128 VISIT(c, expr, val);
3129 VISIT(c, expr, elt);
3130 ADDOP_I(c, MAP_ADD, gen_index + 1);
3131 break;
3132 default:
3133 return 0;
3134 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 compiler_use_next_block(c, skip);
3137 }
3138 compiler_use_next_block(c, if_cleanup);
3139 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3140 compiler_use_next_block(c, anchor);
3141
3142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143}
3144
3145static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003146compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 PyCodeObject *co = NULL;
3150 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003151 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 outermost_iter = ((comprehension_ty)
3154 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003155
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003156 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3157 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (type != COMP_GENEXP) {
3161 int op;
3162 switch (type) {
3163 case COMP_LISTCOMP:
3164 op = BUILD_LIST;
3165 break;
3166 case COMP_SETCOMP:
3167 op = BUILD_SET;
3168 break;
3169 case COMP_DICTCOMP:
3170 op = BUILD_MAP;
3171 break;
3172 default:
3173 PyErr_Format(PyExc_SystemError,
3174 "unknown comprehension type %d", type);
3175 goto error_in_scope;
3176 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 ADDOP_I(c, op, 0);
3179 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 if (!compiler_comprehension_generator(c, generators, 0, elt,
3182 val, type))
3183 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 if (type != COMP_GENEXP) {
3186 ADDOP(c, RETURN_VALUE);
3187 }
3188
3189 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003190 qualname = c->u->u_qualname;
3191 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003193 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 goto error;
3195
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003196 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003198 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 Py_DECREF(co);
3200
3201 VISIT(c, expr, outermost_iter);
3202 ADDOP(c, GET_ITER);
3203 ADDOP_I(c, CALL_FUNCTION, 1);
3204 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003205error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003207error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003208 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 Py_XDECREF(co);
3210 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003211}
3212
3213static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214compiler_genexp(struct compiler *c, expr_ty e)
3215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 static identifier name;
3217 if (!name) {
3218 name = PyUnicode_FromString("<genexpr>");
3219 if (!name)
3220 return 0;
3221 }
3222 assert(e->kind == GeneratorExp_kind);
3223 return compiler_comprehension(c, e, COMP_GENEXP, name,
3224 e->v.GeneratorExp.generators,
3225 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226}
3227
3228static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003229compiler_listcomp(struct compiler *c, expr_ty e)
3230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 static identifier name;
3232 if (!name) {
3233 name = PyUnicode_FromString("<listcomp>");
3234 if (!name)
3235 return 0;
3236 }
3237 assert(e->kind == ListComp_kind);
3238 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3239 e->v.ListComp.generators,
3240 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003241}
3242
3243static int
3244compiler_setcomp(struct compiler *c, expr_ty e)
3245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 static identifier name;
3247 if (!name) {
3248 name = PyUnicode_FromString("<setcomp>");
3249 if (!name)
3250 return 0;
3251 }
3252 assert(e->kind == SetComp_kind);
3253 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3254 e->v.SetComp.generators,
3255 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003256}
3257
3258
3259static int
3260compiler_dictcomp(struct compiler *c, expr_ty e)
3261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 static identifier name;
3263 if (!name) {
3264 name = PyUnicode_FromString("<dictcomp>");
3265 if (!name)
3266 return 0;
3267 }
3268 assert(e->kind == DictComp_kind);
3269 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3270 e->v.DictComp.generators,
3271 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003272}
3273
3274
3275static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276compiler_visit_keyword(struct compiler *c, keyword_ty k)
3277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3279 VISIT(c, expr, k->value);
3280 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281}
3282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 whether they are true or false.
3285
3286 Return values: 1 for true, 0 for false, -1 for non-constant.
3287 */
3288
3289static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003290expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 char *id;
3293 switch (e->kind) {
3294 case Ellipsis_kind:
3295 return 1;
3296 case Num_kind:
3297 return PyObject_IsTrue(e->v.Num.n);
3298 case Str_kind:
3299 return PyObject_IsTrue(e->v.Str.s);
3300 case Name_kind:
3301 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003303 if (id && strcmp(id, "__debug__") == 0)
3304 return !c->c_optimize;
3305 return -1;
3306 case NameConstant_kind: {
3307 PyObject *o = e->v.NameConstant.value;
3308 if (o == Py_None)
3309 return 0;
3310 else if (o == Py_True)
3311 return 1;
3312 else if (o == Py_False)
3313 return 0;
3314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 default:
3316 return -1;
3317 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318}
3319
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320/*
3321 Implements the with statement from PEP 343.
3322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003324
3325 with EXPR as VAR:
3326 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327
Guido van Rossumc2e20742006-02-27 22:32:47 +00003328 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329
Thomas Wouters477c8d52006-05-27 19:21:47 +00003330 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003331 exit = context.__exit__ # not calling it
3332 value = context.__enter__()
3333 try:
3334 VAR = value # if VAR present in the syntax
3335 BLOCK
3336 finally:
3337 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003339 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003341 exit(*exc)
3342 */
3343static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003344compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003345{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003346 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003347 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003348
3349 assert(s->kind == With_kind);
3350
Guido van Rossumc2e20742006-02-27 22:32:47 +00003351 block = compiler_new_block(c);
3352 finally = compiler_new_block(c);
3353 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003354 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003355
Thomas Wouters477c8d52006-05-27 19:21:47 +00003356 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003357 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003358 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003359
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003360 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361 compiler_use_next_block(c, block);
3362 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003363 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003364 }
3365
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003366 if (item->optional_vars) {
3367 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003368 }
3369 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003371 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003372 }
3373
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003374 pos++;
3375 if (pos == asdl_seq_LEN(s->v.With.items))
3376 /* BLOCK code */
3377 VISIT_SEQ(c, stmt, s->v.With.body)
3378 else if (!compiler_with(c, s, pos))
3379 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003380
3381 /* End of try block; start the finally block */
3382 ADDOP(c, POP_BLOCK);
3383 compiler_pop_fblock(c, FINALLY_TRY, block);
3384
3385 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3386 compiler_use_next_block(c, finally);
3387 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003388 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003389
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003390 /* Finally block starts; context.__exit__ is on the stack under
3391 the exception or return information. Just issue our magic
3392 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003393 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003394
3395 /* Finally block ends. */
3396 ADDOP(c, END_FINALLY);
3397 compiler_pop_fblock(c, FINALLY_END, finally);
3398 return 1;
3399}
3400
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401static int
3402compiler_visit_expr(struct compiler *c, expr_ty e)
3403{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003404 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* If expr e has a different line number than the last expr/stmt,
3407 set a new line number for the next instruction.
3408 */
3409 if (e->lineno > c->u->u_lineno) {
3410 c->u->u_lineno = e->lineno;
3411 c->u->u_lineno_set = 0;
3412 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003413 /* Updating the column offset is always harmless. */
3414 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 switch (e->kind) {
3416 case BoolOp_kind:
3417 return compiler_boolop(c, e);
3418 case BinOp_kind:
3419 VISIT(c, expr, e->v.BinOp.left);
3420 VISIT(c, expr, e->v.BinOp.right);
3421 ADDOP(c, binop(c, e->v.BinOp.op));
3422 break;
3423 case UnaryOp_kind:
3424 VISIT(c, expr, e->v.UnaryOp.operand);
3425 ADDOP(c, unaryop(e->v.UnaryOp.op));
3426 break;
3427 case Lambda_kind:
3428 return compiler_lambda(c, e);
3429 case IfExp_kind:
3430 return compiler_ifexp(c, e);
3431 case Dict_kind:
3432 n = asdl_seq_LEN(e->v.Dict.values);
Victor Stinnerad9a0662013-11-19 22:23:20 +01003433 /* BUILD_MAP parameter is only used to preallocate the dictionary,
3434 it doesn't need to be exact */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3436 for (i = 0; i < n; i++) {
3437 VISIT(c, expr,
3438 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3439 VISIT(c, expr,
3440 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3441 ADDOP(c, STORE_MAP);
3442 }
3443 break;
3444 case Set_kind:
3445 n = asdl_seq_LEN(e->v.Set.elts);
3446 VISIT_SEQ(c, expr, e->v.Set.elts);
3447 ADDOP_I(c, BUILD_SET, n);
3448 break;
3449 case GeneratorExp_kind:
3450 return compiler_genexp(c, e);
3451 case ListComp_kind:
3452 return compiler_listcomp(c, e);
3453 case SetComp_kind:
3454 return compiler_setcomp(c, e);
3455 case DictComp_kind:
3456 return compiler_dictcomp(c, e);
3457 case Yield_kind:
3458 if (c->u->u_ste->ste_type != FunctionBlock)
3459 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003460 if (e->v.Yield.value) {
3461 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 }
3463 else {
3464 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3465 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003466 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003468 case YieldFrom_kind:
3469 if (c->u->u_ste->ste_type != FunctionBlock)
3470 return compiler_error(c, "'yield' outside function");
3471 VISIT(c, expr, e->v.YieldFrom.value);
3472 ADDOP(c, GET_ITER);
3473 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3474 ADDOP(c, YIELD_FROM);
3475 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 case Compare_kind:
3477 return compiler_compare(c, e);
3478 case Call_kind:
3479 return compiler_call(c, e);
3480 case Num_kind:
3481 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3482 break;
3483 case Str_kind:
3484 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3485 break;
3486 case Bytes_kind:
3487 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3488 break;
3489 case Ellipsis_kind:
3490 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3491 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003492 case NameConstant_kind:
3493 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3494 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* The following exprs can be assignment targets. */
3496 case Attribute_kind:
3497 if (e->v.Attribute.ctx != AugStore)
3498 VISIT(c, expr, e->v.Attribute.value);
3499 switch (e->v.Attribute.ctx) {
3500 case AugLoad:
3501 ADDOP(c, DUP_TOP);
3502 /* Fall through to load */
3503 case Load:
3504 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3505 break;
3506 case AugStore:
3507 ADDOP(c, ROT_TWO);
3508 /* Fall through to save */
3509 case Store:
3510 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3511 break;
3512 case Del:
3513 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3514 break;
3515 case Param:
3516 default:
3517 PyErr_SetString(PyExc_SystemError,
3518 "param invalid in attribute expression");
3519 return 0;
3520 }
3521 break;
3522 case Subscript_kind:
3523 switch (e->v.Subscript.ctx) {
3524 case AugLoad:
3525 VISIT(c, expr, e->v.Subscript.value);
3526 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3527 break;
3528 case Load:
3529 VISIT(c, expr, e->v.Subscript.value);
3530 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3531 break;
3532 case AugStore:
3533 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3534 break;
3535 case Store:
3536 VISIT(c, expr, e->v.Subscript.value);
3537 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3538 break;
3539 case Del:
3540 VISIT(c, expr, e->v.Subscript.value);
3541 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3542 break;
3543 case Param:
3544 default:
3545 PyErr_SetString(PyExc_SystemError,
3546 "param invalid in subscript expression");
3547 return 0;
3548 }
3549 break;
3550 case Starred_kind:
3551 switch (e->v.Starred.ctx) {
3552 case Store:
3553 /* In all legitimate cases, the Starred node was already replaced
3554 * by compiler_list/compiler_tuple. XXX: is that okay? */
3555 return compiler_error(c,
3556 "starred assignment target must be in a list or tuple");
3557 default:
3558 return compiler_error(c,
3559 "can use starred expression only as assignment target");
3560 }
3561 break;
3562 case Name_kind:
3563 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3564 /* child nodes of List and Tuple will have expr_context set */
3565 case List_kind:
3566 return compiler_list(c, e);
3567 case Tuple_kind:
3568 return compiler_tuple(c, e);
3569 }
3570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571}
3572
3573static int
3574compiler_augassign(struct compiler *c, stmt_ty s)
3575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 expr_ty e = s->v.AugAssign.target;
3577 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 switch (e->kind) {
3582 case Attribute_kind:
3583 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3584 AugLoad, e->lineno, e->col_offset, c->c_arena);
3585 if (auge == NULL)
3586 return 0;
3587 VISIT(c, expr, auge);
3588 VISIT(c, expr, s->v.AugAssign.value);
3589 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3590 auge->v.Attribute.ctx = AugStore;
3591 VISIT(c, expr, auge);
3592 break;
3593 case Subscript_kind:
3594 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3595 AugLoad, e->lineno, e->col_offset, c->c_arena);
3596 if (auge == NULL)
3597 return 0;
3598 VISIT(c, expr, auge);
3599 VISIT(c, expr, s->v.AugAssign.value);
3600 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3601 auge->v.Subscript.ctx = AugStore;
3602 VISIT(c, expr, auge);
3603 break;
3604 case Name_kind:
3605 if (!compiler_nameop(c, e->v.Name.id, Load))
3606 return 0;
3607 VISIT(c, expr, s->v.AugAssign.value);
3608 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3609 return compiler_nameop(c, e->v.Name.id, Store);
3610 default:
3611 PyErr_Format(PyExc_SystemError,
3612 "invalid node type (%d) for augmented assignment",
3613 e->kind);
3614 return 0;
3615 }
3616 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617}
3618
3619static int
3620compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 struct fblockinfo *f;
3623 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3624 PyErr_SetString(PyExc_SystemError,
3625 "too many statically nested blocks");
3626 return 0;
3627 }
3628 f = &c->u->u_fblock[c->u->u_nfblocks++];
3629 f->fb_type = t;
3630 f->fb_block = b;
3631 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632}
3633
3634static void
3635compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 struct compiler_unit *u = c->u;
3638 assert(u->u_nfblocks > 0);
3639 u->u_nfblocks--;
3640 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3641 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642}
3643
Thomas Wouters89f507f2006-12-13 04:49:30 +00003644static int
3645compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 int i;
3647 struct compiler_unit *u = c->u;
3648 for (i = 0; i < u->u_nfblocks; ++i) {
3649 if (u->u_fblock[i].fb_type == LOOP)
3650 return 1;
3651 }
3652 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003653}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654/* Raises a SyntaxError and returns 0.
3655 If something goes wrong, a different exception may be raised.
3656*/
3657
3658static int
3659compiler_error(struct compiler *c, const char *errstr)
3660{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003661 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663
Victor Stinner14e461d2013-08-26 22:28:21 +02003664 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 if (!loc) {
3666 Py_INCREF(Py_None);
3667 loc = Py_None;
3668 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003669 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003670 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (!u)
3672 goto exit;
3673 v = Py_BuildValue("(zO)", errstr, u);
3674 if (!v)
3675 goto exit;
3676 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 Py_DECREF(loc);
3679 Py_XDECREF(u);
3680 Py_XDECREF(v);
3681 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682}
3683
3684static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685compiler_handle_subscr(struct compiler *c, const char *kind,
3686 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 /* XXX this code is duplicated */
3691 switch (ctx) {
3692 case AugLoad: /* fall through to Load */
3693 case Load: op = BINARY_SUBSCR; break;
3694 case AugStore:/* fall through to Store */
3695 case Store: op = STORE_SUBSCR; break;
3696 case Del: op = DELETE_SUBSCR; break;
3697 case Param:
3698 PyErr_Format(PyExc_SystemError,
3699 "invalid %s kind %d in subscript\n",
3700 kind, ctx);
3701 return 0;
3702 }
3703 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003704 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 }
3706 else if (ctx == AugStore) {
3707 ADDOP(c, ROT_THREE);
3708 }
3709 ADDOP(c, op);
3710 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711}
3712
3713static int
3714compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 int n = 2;
3717 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 /* only handles the cases where BUILD_SLICE is emitted */
3720 if (s->v.Slice.lower) {
3721 VISIT(c, expr, s->v.Slice.lower);
3722 }
3723 else {
3724 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3725 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (s->v.Slice.upper) {
3728 VISIT(c, expr, s->v.Slice.upper);
3729 }
3730 else {
3731 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3732 }
3733
3734 if (s->v.Slice.step) {
3735 n++;
3736 VISIT(c, expr, s->v.Slice.step);
3737 }
3738 ADDOP_I(c, BUILD_SLICE, n);
3739 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740}
3741
3742static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3744 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 switch (s->kind) {
3747 case Slice_kind:
3748 return compiler_slice(c, s, ctx);
3749 case Index_kind:
3750 VISIT(c, expr, s->v.Index.value);
3751 break;
3752 case ExtSlice_kind:
3753 default:
3754 PyErr_SetString(PyExc_SystemError,
3755 "extended slice invalid in nested slice");
3756 return 0;
3757 }
3758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759}
3760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761static int
3762compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 char * kindname = NULL;
3765 switch (s->kind) {
3766 case Index_kind:
3767 kindname = "index";
3768 if (ctx != AugStore) {
3769 VISIT(c, expr, s->v.Index.value);
3770 }
3771 break;
3772 case Slice_kind:
3773 kindname = "slice";
3774 if (ctx != AugStore) {
3775 if (!compiler_slice(c, s, ctx))
3776 return 0;
3777 }
3778 break;
3779 case ExtSlice_kind:
3780 kindname = "extended slice";
3781 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01003782 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 for (i = 0; i < n; i++) {
3784 slice_ty sub = (slice_ty)asdl_seq_GET(
3785 s->v.ExtSlice.dims, i);
3786 if (!compiler_visit_nested_slice(c, sub, ctx))
3787 return 0;
3788 }
3789 ADDOP_I(c, BUILD_TUPLE, n);
3790 }
3791 break;
3792 default:
3793 PyErr_Format(PyExc_SystemError,
3794 "invalid subscript kind %d", s->kind);
3795 return 0;
3796 }
3797 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798}
3799
Thomas Wouters89f507f2006-12-13 04:49:30 +00003800/* End of the compiler section, beginning of the assembler section */
3801
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802/* do depth-first search of basic block graph, starting with block.
3803 post records the block indices in post-order.
3804
3805 XXX must handle implicit jumps from one block to next
3806*/
3807
Thomas Wouters89f507f2006-12-13 04:49:30 +00003808struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 PyObject *a_bytecode; /* string containing bytecode */
3810 int a_offset; /* offset into bytecode */
3811 int a_nblocks; /* number of reachable blocks */
3812 basicblock **a_postorder; /* list of blocks in dfs postorder */
3813 PyObject *a_lnotab; /* string containing lnotab */
3814 int a_lnotab_off; /* offset into lnotab */
3815 int a_lineno; /* last lineno of emitted instruction */
3816 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003817};
3818
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819static void
3820dfs(struct compiler *c, basicblock *b, struct assembler *a)
3821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 int i;
3823 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (b->b_seen)
3826 return;
3827 b->b_seen = 1;
3828 if (b->b_next != NULL)
3829 dfs(c, b->b_next, a);
3830 for (i = 0; i < b->b_iused; i++) {
3831 instr = &b->b_instr[i];
3832 if (instr->i_jrel || instr->i_jabs)
3833 dfs(c, instr->i_target, a);
3834 }
3835 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836}
3837
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003838static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003839stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3840{
Larry Hastings3a907972013-11-23 14:49:22 -08003841 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 struct instr *instr;
3843 if (b->b_seen || b->b_startdepth >= depth)
3844 return maxdepth;
3845 b->b_seen = 1;
3846 b->b_startdepth = depth;
3847 for (i = 0; i < b->b_iused; i++) {
3848 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08003849 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
3850 if (effect == PY_INVALID_STACK_EFFECT) {
3851 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
3852 Py_FatalError("PyCompile_OpcodeStackEffect()");
3853 }
3854 depth += effect;
3855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 if (depth > maxdepth)
3857 maxdepth = depth;
3858 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3859 if (instr->i_jrel || instr->i_jabs) {
3860 target_depth = depth;
3861 if (instr->i_opcode == FOR_ITER) {
3862 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02003863 }
3864 else if (instr->i_opcode == SETUP_FINALLY ||
3865 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 target_depth = depth+3;
3867 if (target_depth > maxdepth)
3868 maxdepth = target_depth;
3869 }
Antoine Pitrou99614052014-05-23 11:46:03 +02003870 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
3871 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
3872 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 maxdepth = stackdepth_walk(c, instr->i_target,
3874 target_depth, maxdepth);
3875 if (instr->i_opcode == JUMP_ABSOLUTE ||
3876 instr->i_opcode == JUMP_FORWARD) {
3877 goto out; /* remaining code is dead */
3878 }
3879 }
3880 }
3881 if (b->b_next)
3882 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 b->b_seen = 0;
3885 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886}
3887
3888/* Find the flow path that needs the largest stack. We assume that
3889 * cycles in the flow graph have no net effect on the stack depth.
3890 */
3891static int
3892stackdepth(struct compiler *c)
3893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 basicblock *b, *entryblock;
3895 entryblock = NULL;
3896 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3897 b->b_seen = 0;
3898 b->b_startdepth = INT_MIN;
3899 entryblock = b;
3900 }
3901 if (!entryblock)
3902 return 0;
3903 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904}
3905
3906static int
3907assemble_init(struct assembler *a, int nblocks, int firstlineno)
3908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 memset(a, 0, sizeof(struct assembler));
3910 a->a_lineno = firstlineno;
3911 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3912 if (!a->a_bytecode)
3913 return 0;
3914 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3915 if (!a->a_lnotab)
3916 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01003917 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 PyErr_NoMemory();
3919 return 0;
3920 }
3921 a->a_postorder = (basicblock **)PyObject_Malloc(
3922 sizeof(basicblock *) * nblocks);
3923 if (!a->a_postorder) {
3924 PyErr_NoMemory();
3925 return 0;
3926 }
3927 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928}
3929
3930static void
3931assemble_free(struct assembler *a)
3932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 Py_XDECREF(a->a_bytecode);
3934 Py_XDECREF(a->a_lnotab);
3935 if (a->a_postorder)
3936 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003937}
3938
3939/* Return the size of a basic block in bytes. */
3940
3941static int
3942instrsize(struct instr *instr)
3943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 if (!instr->i_hasarg)
3945 return 1; /* 1 byte for the opcode*/
3946 if (instr->i_oparg > 0xffff)
3947 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3948 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949}
3950
3951static int
3952blocksize(basicblock *b)
3953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 int i;
3955 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 for (i = 0; i < b->b_iused; i++)
3958 size += instrsize(&b->b_instr[i]);
3959 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003960}
3961
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003962/* Appends a pair to the end of the line number table, a_lnotab, representing
3963 the instruction's bytecode offset and line number. See
3964 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003965
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003966static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003970 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 d_bytecode = a->a_offset - a->a_lineno_off;
3974 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 assert(d_bytecode >= 0);
3977 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 if(d_bytecode == 0 && d_lineno == 0)
3980 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 if (d_bytecode > 255) {
3983 int j, nbytes, ncodes = d_bytecode / 255;
3984 nbytes = a->a_lnotab_off + 2 * ncodes;
3985 len = PyBytes_GET_SIZE(a->a_lnotab);
3986 if (nbytes >= len) {
3987 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3988 len = nbytes;
3989 else if (len <= INT_MAX / 2)
3990 len *= 2;
3991 else {
3992 PyErr_NoMemory();
3993 return 0;
3994 }
3995 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3996 return 0;
3997 }
3998 lnotab = (unsigned char *)
3999 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4000 for (j = 0; j < ncodes; j++) {
4001 *lnotab++ = 255;
4002 *lnotab++ = 0;
4003 }
4004 d_bytecode -= ncodes * 255;
4005 a->a_lnotab_off += ncodes * 2;
4006 }
4007 assert(d_bytecode <= 255);
4008 if (d_lineno > 255) {
4009 int j, nbytes, ncodes = d_lineno / 255;
4010 nbytes = a->a_lnotab_off + 2 * ncodes;
4011 len = PyBytes_GET_SIZE(a->a_lnotab);
4012 if (nbytes >= len) {
4013 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4014 len = nbytes;
4015 else if (len <= INT_MAX / 2)
4016 len *= 2;
4017 else {
4018 PyErr_NoMemory();
4019 return 0;
4020 }
4021 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4022 return 0;
4023 }
4024 lnotab = (unsigned char *)
4025 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4026 *lnotab++ = d_bytecode;
4027 *lnotab++ = 255;
4028 d_bytecode = 0;
4029 for (j = 1; j < ncodes; j++) {
4030 *lnotab++ = 0;
4031 *lnotab++ = 255;
4032 }
4033 d_lineno -= ncodes * 255;
4034 a->a_lnotab_off += ncodes * 2;
4035 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 len = PyBytes_GET_SIZE(a->a_lnotab);
4038 if (a->a_lnotab_off + 2 >= len) {
4039 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4040 return 0;
4041 }
4042 lnotab = (unsigned char *)
4043 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 a->a_lnotab_off += 2;
4046 if (d_bytecode) {
4047 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004048 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 }
4050 else { /* First line of a block; def stmt, etc. */
4051 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004052 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 }
4054 a->a_lineno = i->i_lineno;
4055 a->a_lineno_off = a->a_offset;
4056 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004057}
4058
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004059/* assemble_emit()
4060 Extend the bytecode with a new instruction.
4061 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004062*/
4063
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004064static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 int size, arg = 0, ext = 0;
4068 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4069 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 size = instrsize(i);
4072 if (i->i_hasarg) {
4073 arg = i->i_oparg;
4074 ext = arg >> 16;
4075 }
4076 if (i->i_lineno && !assemble_lnotab(a, i))
4077 return 0;
4078 if (a->a_offset + size >= len) {
4079 if (len > PY_SSIZE_T_MAX / 2)
4080 return 0;
4081 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4082 return 0;
4083 }
4084 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4085 a->a_offset += size;
4086 if (size == 6) {
4087 assert(i->i_hasarg);
4088 *code++ = (char)EXTENDED_ARG;
4089 *code++ = ext & 0xff;
4090 *code++ = ext >> 8;
4091 arg &= 0xffff;
4092 }
4093 *code++ = i->i_opcode;
4094 if (i->i_hasarg) {
4095 assert(size == 3 || size == 6);
4096 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004097 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 }
4099 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004100}
4101
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004102static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 basicblock *b;
4106 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4107 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 /* Compute the size of each block and fixup jump args.
4110 Replace block pointer with position in bytecode. */
4111 do {
4112 totsize = 0;
4113 for (i = a->a_nblocks - 1; i >= 0; i--) {
4114 b = a->a_postorder[i];
4115 bsize = blocksize(b);
4116 b->b_offset = totsize;
4117 totsize += bsize;
4118 }
4119 last_extended_arg_count = extended_arg_count;
4120 extended_arg_count = 0;
4121 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4122 bsize = b->b_offset;
4123 for (i = 0; i < b->b_iused; i++) {
4124 struct instr *instr = &b->b_instr[i];
4125 /* Relative jumps are computed relative to
4126 the instruction pointer after fetching
4127 the jump instruction.
4128 */
4129 bsize += instrsize(instr);
4130 if (instr->i_jabs)
4131 instr->i_oparg = instr->i_target->b_offset;
4132 else if (instr->i_jrel) {
4133 int delta = instr->i_target->b_offset - bsize;
4134 instr->i_oparg = delta;
4135 }
4136 else
4137 continue;
4138 if (instr->i_oparg > 0xffff)
4139 extended_arg_count++;
4140 }
4141 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 /* XXX: This is an awful hack that could hurt performance, but
4144 on the bright side it should work until we come up
4145 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 The issue is that in the first loop blocksize() is called
4148 which calls instrsize() which requires i_oparg be set
4149 appropriately. There is a bootstrap problem because
4150 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 So we loop until we stop seeing new EXTENDED_ARGs.
4153 The only EXTENDED_ARGs that could be popping up are
4154 ones in jump instructions. So this should converge
4155 fairly quickly.
4156 */
4157 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004158}
4159
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004160static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004161dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 PyObject *tuple, *k, *v;
4164 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 tuple = PyTuple_New(size);
4167 if (tuple == NULL)
4168 return NULL;
4169 while (PyDict_Next(dict, &pos, &k, &v)) {
4170 i = PyLong_AS_LONG(v);
4171 /* The keys of the dictionary are tuples. (see compiler_add_o)
4172 The object we want is always first, though. */
4173 k = PyTuple_GET_ITEM(k, 0);
4174 Py_INCREF(k);
4175 assert((i - offset) < size);
4176 assert((i - offset) >= 0);
4177 PyTuple_SET_ITEM(tuple, i - offset, k);
4178 }
4179 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004180}
4181
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004182static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004186 int flags = 0;
4187 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004189 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (!ste->ste_unoptimized)
4191 flags |= CO_OPTIMIZED;
4192 if (ste->ste_nested)
4193 flags |= CO_NESTED;
4194 if (ste->ste_generator)
4195 flags |= CO_GENERATOR;
4196 if (ste->ste_varargs)
4197 flags |= CO_VARARGS;
4198 if (ste->ste_varkeywords)
4199 flags |= CO_VARKEYWORDS;
4200 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* (Only) inherit compilerflags in PyCF_MASK */
4203 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 n = PyDict_Size(c->u->u_freevars);
4206 if (n < 0)
4207 return -1;
4208 if (n == 0) {
4209 n = PyDict_Size(c->u->u_cellvars);
4210 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004211 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004213 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 }
4215 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004218}
4219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220static PyCodeObject *
4221makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 PyObject *tmp;
4224 PyCodeObject *co = NULL;
4225 PyObject *consts = NULL;
4226 PyObject *names = NULL;
4227 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 PyObject *name = NULL;
4229 PyObject *freevars = NULL;
4230 PyObject *cellvars = NULL;
4231 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004232 Py_ssize_t nlocals;
4233 int nlocals_int;
4234 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004235 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 tmp = dict_keys_inorder(c->u->u_consts, 0);
4238 if (!tmp)
4239 goto error;
4240 consts = PySequence_List(tmp); /* optimize_code requires a list */
4241 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 names = dict_keys_inorder(c->u->u_names, 0);
4244 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4245 if (!consts || !names || !varnames)
4246 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4249 if (!cellvars)
4250 goto error;
4251 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4252 if (!freevars)
4253 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004256 assert(nlocals < INT_MAX);
4257 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 flags = compute_code_flags(c);
4260 if (flags < 0)
4261 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4264 if (!bytecode)
4265 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4268 if (!tmp)
4269 goto error;
4270 Py_DECREF(consts);
4271 consts = tmp;
4272
Victor Stinnerf8e32212013-11-19 23:56:34 +01004273 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4274 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4275 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004276 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 bytecode, consts, names, varnames,
4278 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004279 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 c->u->u_firstlineno,
4281 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004282 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 Py_XDECREF(consts);
4284 Py_XDECREF(names);
4285 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 Py_XDECREF(name);
4287 Py_XDECREF(freevars);
4288 Py_XDECREF(cellvars);
4289 Py_XDECREF(bytecode);
4290 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004291}
4292
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004293
4294/* For debugging purposes only */
4295#if 0
4296static void
4297dump_instr(const struct instr *i)
4298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 const char *jrel = i->i_jrel ? "jrel " : "";
4300 const char *jabs = i->i_jabs ? "jabs " : "";
4301 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 *arg = '\0';
4304 if (i->i_hasarg)
4305 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4308 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004309}
4310
4311static void
4312dump_basicblock(const basicblock *b)
4313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 const char *seen = b->b_seen ? "seen " : "";
4315 const char *b_return = b->b_return ? "return " : "";
4316 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4317 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4318 if (b->b_instr) {
4319 int i;
4320 for (i = 0; i < b->b_iused; i++) {
4321 fprintf(stderr, " [%02d] ", i);
4322 dump_instr(b->b_instr + i);
4323 }
4324 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004325}
4326#endif
4327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328static PyCodeObject *
4329assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 basicblock *b, *entryblock;
4332 struct assembler a;
4333 int i, j, nblocks;
4334 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 /* Make sure every block that falls off the end returns None.
4337 XXX NEXT_BLOCK() isn't quite right, because if the last
4338 block ends with a jump or return b_next shouldn't set.
4339 */
4340 if (!c->u->u_curblock->b_return) {
4341 NEXT_BLOCK(c);
4342 if (addNone)
4343 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4344 ADDOP(c, RETURN_VALUE);
4345 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 nblocks = 0;
4348 entryblock = NULL;
4349 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4350 nblocks++;
4351 entryblock = b;
4352 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 /* Set firstlineno if it wasn't explicitly set. */
4355 if (!c->u->u_firstlineno) {
4356 if (entryblock && entryblock->b_instr)
4357 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4358 else
4359 c->u->u_firstlineno = 1;
4360 }
4361 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4362 goto error;
4363 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 /* Can't modify the bytecode after computing jump offsets. */
4366 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 /* Emit code in reverse postorder from dfs. */
4369 for (i = a.a_nblocks - 1; i >= 0; i--) {
4370 b = a.a_postorder[i];
4371 for (j = 0; j < b->b_iused; j++)
4372 if (!assemble_emit(&a, &b->b_instr[j]))
4373 goto error;
4374 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4377 goto error;
4378 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4379 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 assemble_free(&a);
4384 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004385}
Georg Brandl8334fd92010-12-04 10:26:46 +00004386
4387#undef PyAST_Compile
4388PyAPI_FUNC(PyCodeObject *)
4389PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4390 PyArena *arena)
4391{
4392 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4393}
4394