blob: efd48076135e34dc27f2739ee0f7057604a5aeaa [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,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400198 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500199static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400200static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000201
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202static PyCodeObject *assemble(struct compiler *, int addNone);
203static PyObject *__doc__;
204
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400205#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000206
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000208_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 /* Name mangling: __private becomes _classname__private.
211 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200212 PyObject *result;
213 size_t nlen, plen, ipriv;
214 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200216 PyUnicode_READ_CHAR(ident, 0) != '_' ||
217 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 Py_INCREF(ident);
219 return ident;
220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200221 nlen = PyUnicode_GET_LENGTH(ident);
222 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 The only time a name with a dot can occur is when
226 we are compiling an import statement that has a
227 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 TODO(jhylton): Decide whether we want to support
230 mangling of the module name, e.g. __M.X.
231 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
233 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
234 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_INCREF(ident);
236 return ident; /* Don't mangle __whatever__ */
237 }
238 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200239 ipriv = 0;
240 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
241 ipriv++;
242 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_INCREF(ident);
244 return ident; /* Don't mangle if class is just underscores */
245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200246 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000247
Antoine Pitrou55bff892013-04-06 21:21:04 +0200248 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
249 PyErr_SetString(PyExc_OverflowError,
250 "private identifier too large to be mangled");
251 return NULL;
252 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
255 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
256 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
257
258 result = PyUnicode_New(1 + nlen + plen, maxchar);
259 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200261 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
262 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200263 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
264 Py_DECREF(result);
265 return NULL;
266 }
267 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
268 Py_DECREF(result);
269 return NULL;
270 }
Victor Stinner8f825062012-04-27 13:55:39 +0200271 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200272 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000273}
274
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000275static int
276compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 c->c_stack = PyList_New(0);
281 if (!c->c_stack)
282 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285}
286
287PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200288PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
289 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 struct compiler c;
292 PyCodeObject *co = NULL;
293 PyCompilerFlags local_flags;
294 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (!__doc__) {
297 __doc__ = PyUnicode_InternFromString("__doc__");
298 if (!__doc__)
299 return NULL;
300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (!compiler_init(&c))
303 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200304 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 c.c_filename = filename;
306 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200307 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (c.c_future == NULL)
309 goto finally;
310 if (!flags) {
311 local_flags.cf_flags = 0;
312 flags = &local_flags;
313 }
314 merged = c.c_future->ff_features | flags->cf_flags;
315 c.c_future->ff_features = merged;
316 flags->cf_flags = merged;
317 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000318 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320
Victor Stinner14e461d2013-08-26 22:28:21 +0200321 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (c.c_st == NULL) {
323 if (!PyErr_Occurred())
324 PyErr_SetString(PyExc_SystemError, "no symtable");
325 goto finally;
326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Thomas Wouters1175c432006-02-27 22:49:54 +0000330 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 compiler_free(&c);
332 assert(co || PyErr_Occurred());
333 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334}
335
336PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200337PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
338 int optimize, PyArena *arena)
339{
340 PyObject *filename;
341 PyCodeObject *co;
342 filename = PyUnicode_DecodeFSDefault(filename_str);
343 if (filename == NULL)
344 return NULL;
345 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
346 Py_DECREF(filename);
347 return co;
348
349}
350
351PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352PyNode_Compile(struct _node *n, const char *filename)
353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyCodeObject *co = NULL;
355 mod_ty mod;
356 PyArena *arena = PyArena_New();
357 if (!arena)
358 return NULL;
359 mod = PyAST_FromNode(n, NULL, filename, arena);
360 if (mod)
361 co = PyAST_Compile(mod, filename, NULL, arena);
362 PyArena_Free(arena);
363 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000364}
365
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000366static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (c->c_st)
370 PySymtable_Free(c->c_st);
371 if (c->c_future)
372 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200373 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000375}
376
Guido van Rossum79f25d91997-04-29 20:08:16 +0000377static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 Py_ssize_t i, n;
381 PyObject *v, *k;
382 PyObject *dict = PyDict_New();
383 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 n = PyList_Size(list);
386 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100387 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (!v) {
389 Py_DECREF(dict);
390 return NULL;
391 }
392 k = PyList_GET_ITEM(list, i);
393 k = PyTuple_Pack(2, k, k->ob_type);
394 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
395 Py_XDECREF(k);
396 Py_DECREF(v);
397 Py_DECREF(dict);
398 return NULL;
399 }
400 Py_DECREF(k);
401 Py_DECREF(v);
402 }
403 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404}
405
406/* Return new dict containing names from src that match scope(s).
407
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410values are integers, starting at offset and increasing by one for
411each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412*/
413
414static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100415dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000416{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700417 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500419 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 assert(offset >= 0);
422 if (dest == NULL)
423 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000424
Meador Inge2ca63152012-07-18 14:20:11 -0500425 /* Sort the keys so that we have a deterministic order on the indexes
426 saved in the returned dictionary. These indexes are used as indexes
427 into the free and cell var storage. Therefore if they aren't
428 deterministic, then the generated bytecode is not deterministic.
429 */
430 sorted_keys = PyDict_Keys(src);
431 if (sorted_keys == NULL)
432 return NULL;
433 if (PyList_Sort(sorted_keys) != 0) {
434 Py_DECREF(sorted_keys);
435 return NULL;
436 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500437 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500438
439 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* XXX this should probably be a macro in symtable.h */
441 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500442 k = PyList_GET_ITEM(sorted_keys, key_i);
443 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(PyLong_Check(v));
445 vi = PyLong_AS_LONG(v);
446 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100449 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500451 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 Py_DECREF(dest);
453 return NULL;
454 }
455 i++;
456 tuple = PyTuple_Pack(2, k, k->ob_type);
457 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500458 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 Py_DECREF(item);
460 Py_DECREF(dest);
461 Py_XDECREF(tuple);
462 return NULL;
463 }
464 Py_DECREF(item);
465 Py_DECREF(tuple);
466 }
467 }
Meador Inge2ca63152012-07-18 14:20:11 -0500468 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000470}
471
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472static void
473compiler_unit_check(struct compiler_unit *u)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 basicblock *block;
476 for (block = u->u_blocks; block != NULL; block = block->b_list) {
477 assert((void *)block != (void *)0xcbcbcbcb);
478 assert((void *)block != (void *)0xfbfbfbfb);
479 assert((void *)block != (void *)0xdbdbdbdb);
480 if (block->b_instr != NULL) {
481 assert(block->b_ialloc > 0);
482 assert(block->b_iused > 0);
483 assert(block->b_ialloc >= block->b_iused);
484 }
485 else {
486 assert (block->b_iused == 0);
487 assert (block->b_ialloc == 0);
488 }
489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490}
491
492static void
493compiler_unit_free(struct compiler_unit *u)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 compiler_unit_check(u);
498 b = u->u_blocks;
499 while (b != NULL) {
500 if (b->b_instr)
501 PyObject_Free((void *)b->b_instr);
502 next = b->b_list;
503 PyObject_Free((void *)b);
504 b = next;
505 }
506 Py_CLEAR(u->u_ste);
507 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400508 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_CLEAR(u->u_consts);
510 Py_CLEAR(u->u_names);
511 Py_CLEAR(u->u_varnames);
512 Py_CLEAR(u->u_freevars);
513 Py_CLEAR(u->u_cellvars);
514 Py_CLEAR(u->u_private);
515 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516}
517
518static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100519compiler_enter_scope(struct compiler *c, identifier name,
520 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
525 struct compiler_unit));
526 if (!u) {
527 PyErr_NoMemory();
528 return 0;
529 }
530 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100531 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 u->u_argcount = 0;
533 u->u_kwonlyargcount = 0;
534 u->u_ste = PySymtable_Lookup(c->c_st, key);
535 if (!u->u_ste) {
536 compiler_unit_free(u);
537 return 0;
538 }
539 Py_INCREF(name);
540 u->u_name = name;
541 u->u_varnames = list2dict(u->u_ste->ste_varnames);
542 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
543 if (!u->u_varnames || !u->u_cellvars) {
544 compiler_unit_free(u);
545 return 0;
546 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500547 if (u->u_ste->ste_needs_class_closure) {
548 /* Cook up a implicit __class__ cell. */
549 _Py_IDENTIFIER(__class__);
550 PyObject *tuple, *name, *zero;
551 int res;
552 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
553 assert(PyDict_Size(u->u_cellvars) == 0);
554 name = _PyUnicode_FromId(&PyId___class__);
555 if (!name) {
556 compiler_unit_free(u);
557 return 0;
558 }
559 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
560 if (!tuple) {
561 compiler_unit_free(u);
562 return 0;
563 }
564 zero = PyLong_FromLong(0);
565 if (!zero) {
566 Py_DECREF(tuple);
567 compiler_unit_free(u);
568 return 0;
569 }
570 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
571 Py_DECREF(tuple);
572 Py_DECREF(zero);
573 if (res < 0) {
574 compiler_unit_free(u);
575 return 0;
576 }
577 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
580 PyDict_Size(u->u_cellvars));
581 if (!u->u_freevars) {
582 compiler_unit_free(u);
583 return 0;
584 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 u->u_blocks = NULL;
587 u->u_nfblocks = 0;
588 u->u_firstlineno = lineno;
589 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000590 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 u->u_lineno_set = 0;
592 u->u_consts = PyDict_New();
593 if (!u->u_consts) {
594 compiler_unit_free(u);
595 return 0;
596 }
597 u->u_names = PyDict_New();
598 if (!u->u_names) {
599 compiler_unit_free(u);
600 return 0;
601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 /* Push the old compiler_unit on the stack. */
606 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400607 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
609 Py_XDECREF(capsule);
610 compiler_unit_free(u);
611 return 0;
612 }
613 Py_DECREF(capsule);
614 u->u_private = c->u->u_private;
615 Py_XINCREF(u->u_private);
616 }
617 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 c->c_nestlevel++;
620 if (compiler_use_new_block(c) == NULL)
621 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400623 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
624 if (!compiler_set_qualname(c))
625 return 0;
626 }
627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629}
630
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000631static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632compiler_exit_scope(struct compiler *c)
633{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100634 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 c->c_nestlevel--;
638 compiler_unit_free(c->u);
639 /* Restore c->u to the parent unit. */
640 n = PyList_GET_SIZE(c->c_stack) - 1;
641 if (n >= 0) {
642 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400643 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 assert(c->u);
645 /* we are deleting from a list so this really shouldn't fail */
646 if (PySequence_DelItem(c->c_stack, n) < 0)
647 Py_FatalError("compiler_exit_scope()");
648 compiler_unit_check(c->u);
649 }
650 else
651 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653}
654
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400655static int
656compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100657{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100658 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400659 _Py_static_string(dot_locals, ".<locals>");
660 Py_ssize_t stack_size;
661 struct compiler_unit *u = c->u;
662 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400664 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100665 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400666 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667 if (stack_size > 1) {
668 int scope, force_global = 0;
669 struct compiler_unit *parent;
670 PyObject *mangled, *capsule;
671
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400672 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400673 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 assert(parent);
675
676 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) {
677 assert(u->u_name);
678 mangled = _Py_Mangle(parent->u_private, u->u_name);
679 if (!mangled)
680 return 0;
681 scope = PyST_GetScope(parent->u_ste, mangled);
682 Py_DECREF(mangled);
683 assert(scope != GLOBAL_IMPLICIT);
684 if (scope == GLOBAL_EXPLICIT)
685 force_global = 1;
686 }
687
688 if (!force_global) {
689 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
690 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
691 dot_locals_str = _PyUnicode_FromId(&dot_locals);
692 if (dot_locals_str == NULL)
693 return 0;
694 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
695 if (base == NULL)
696 return 0;
697 }
698 else {
699 Py_INCREF(parent->u_qualname);
700 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400701 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100702 }
703 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400704
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 if (base != NULL) {
706 dot_str = _PyUnicode_FromId(&dot);
707 if (dot_str == NULL) {
708 Py_DECREF(base);
709 return 0;
710 }
711 name = PyUnicode_Concat(base, dot_str);
712 Py_DECREF(base);
713 if (name == NULL)
714 return 0;
715 PyUnicode_Append(&name, u->u_name);
716 if (name == NULL)
717 return 0;
718 }
719 else {
720 Py_INCREF(u->u_name);
721 name = u->u_name;
722 }
723 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100724
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400725 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100726}
727
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000728/* Allocate a new block and return a pointer to it.
729 Returns NULL on error.
730*/
731
732static basicblock *
733compiler_new_block(struct compiler *c)
734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 basicblock *b;
736 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 u = c->u;
739 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
740 if (b == NULL) {
741 PyErr_NoMemory();
742 return NULL;
743 }
744 memset((void *)b, 0, sizeof(basicblock));
745 /* Extend the singly linked list of blocks with new block. */
746 b->b_list = u->u_blocks;
747 u->u_blocks = b;
748 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749}
750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751static basicblock *
752compiler_use_new_block(struct compiler *c)
753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 basicblock *block = compiler_new_block(c);
755 if (block == NULL)
756 return NULL;
757 c->u->u_curblock = block;
758 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759}
760
761static basicblock *
762compiler_next_block(struct compiler *c)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 basicblock *block = compiler_new_block(c);
765 if (block == NULL)
766 return NULL;
767 c->u->u_curblock->b_next = block;
768 c->u->u_curblock = block;
769 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
772static basicblock *
773compiler_use_next_block(struct compiler *c, basicblock *block)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 assert(block != NULL);
776 c->u->u_curblock->b_next = block;
777 c->u->u_curblock = block;
778 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
781/* Returns the offset of the next instruction in the current block's
782 b_instr array. Resizes the b_instr as necessary.
783 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000784*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786static int
787compiler_next_instr(struct compiler *c, basicblock *b)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(b != NULL);
790 if (b->b_instr == NULL) {
791 b->b_instr = (struct instr *)PyObject_Malloc(
792 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
793 if (b->b_instr == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 b->b_ialloc = DEFAULT_BLOCK_SIZE;
798 memset((char *)b->b_instr, 0,
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 }
801 else if (b->b_iused == b->b_ialloc) {
802 struct instr *tmp;
803 size_t oldsize, newsize;
804 oldsize = b->b_ialloc * sizeof(struct instr);
805 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (oldsize > (PY_SIZE_MAX >> 1)) {
808 PyErr_NoMemory();
809 return -1;
810 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (newsize == 0) {
813 PyErr_NoMemory();
814 return -1;
815 }
816 b->b_ialloc <<= 1;
817 tmp = (struct instr *)PyObject_Realloc(
818 (void *)b->b_instr, newsize);
819 if (tmp == NULL) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_instr = tmp;
824 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
825 }
826 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827}
828
Christian Heimes2202f872008-02-06 14:31:34 +0000829/* Set the i_lineno member of the instruction at offset off if the
830 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 already been set. If it has been set, the call has no effect.
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833 The line number is reset in the following cases:
834 - when entering a new scope
835 - on each statement
836 - on each expression that start a new line
837 - before the "except" clause
838 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841static void
842compiler_set_lineno(struct compiler *c, int off)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 basicblock *b;
845 if (c->u->u_lineno_set)
846 return;
847 c->u->u_lineno_set = 1;
848 b = c->u->u_curblock;
849 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850}
851
Larry Hastings3a907972013-11-23 14:49:22 -0800852int
853PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 switch (opcode) {
856 case POP_TOP:
857 return -1;
858 case ROT_TWO:
859 case ROT_THREE:
860 return 0;
861 case DUP_TOP:
862 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000863 case DUP_TOP_TWO:
864 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 case UNARY_POSITIVE:
867 case UNARY_NEGATIVE:
868 case UNARY_NOT:
869 case UNARY_INVERT:
870 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case SET_ADD:
873 case LIST_APPEND:
874 return -1;
875 case MAP_ADD:
876 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case BINARY_POWER:
879 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400880 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case BINARY_MODULO:
882 case BINARY_ADD:
883 case BINARY_SUBTRACT:
884 case BINARY_SUBSCR:
885 case BINARY_FLOOR_DIVIDE:
886 case BINARY_TRUE_DIVIDE:
887 return -1;
888 case INPLACE_FLOOR_DIVIDE:
889 case INPLACE_TRUE_DIVIDE:
890 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case INPLACE_ADD:
893 case INPLACE_SUBTRACT:
894 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400895 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_MODULO:
897 return -1;
898 case STORE_SUBSCR:
899 return -3;
900 case STORE_MAP:
901 return -2;
902 case DELETE_SUBSCR:
903 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case BINARY_LSHIFT:
906 case BINARY_RSHIFT:
907 case BINARY_AND:
908 case BINARY_XOR:
909 case BINARY_OR:
910 return -1;
911 case INPLACE_POWER:
912 return -1;
913 case GET_ITER:
914 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case PRINT_EXPR:
917 return -1;
918 case LOAD_BUILD_CLASS:
919 return 1;
920 case INPLACE_LSHIFT:
921 case INPLACE_RSHIFT:
922 case INPLACE_AND:
923 case INPLACE_XOR:
924 case INPLACE_OR:
925 return -1;
926 case BREAK_LOOP:
927 return 0;
928 case SETUP_WITH:
929 return 7;
930 case WITH_CLEANUP:
931 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case RETURN_VALUE:
933 return -1;
934 case IMPORT_STAR:
935 return -1;
936 case YIELD_VALUE:
937 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500938 case YIELD_FROM:
939 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case POP_BLOCK:
941 return 0;
942 case POP_EXCEPT:
943 return 0; /* -3 except if bad bytecode */
944 case END_FINALLY:
945 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case STORE_NAME:
948 return -1;
949 case DELETE_NAME:
950 return 0;
951 case UNPACK_SEQUENCE:
952 return oparg-1;
953 case UNPACK_EX:
954 return (oparg&0xFF) + (oparg>>8);
955 case FOR_ITER:
956 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case STORE_ATTR:
959 return -2;
960 case DELETE_ATTR:
961 return -1;
962 case STORE_GLOBAL:
963 return -1;
964 case DELETE_GLOBAL:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case LOAD_CONST:
967 return 1;
968 case LOAD_NAME:
969 return 1;
970 case BUILD_TUPLE:
971 case BUILD_LIST:
972 case BUILD_SET:
973 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400974 case BUILD_LIST_UNPACK:
975 case BUILD_TUPLE_UNPACK:
976 case BUILD_SET_UNPACK:
977 case BUILD_MAP_UNPACK:
978 return 1 - oparg;
979 case BUILD_MAP_UNPACK_WITH_CALL:
980 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case BUILD_MAP:
982 return 1;
983 case LOAD_ATTR:
984 return 0;
985 case COMPARE_OP:
986 return -1;
987 case IMPORT_NAME:
988 return -1;
989 case IMPORT_FROM:
990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case JUMP_FORWARD:
993 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
994 case JUMP_IF_FALSE_OR_POP: /* "" */
995 case JUMP_ABSOLUTE:
996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case POP_JUMP_IF_FALSE:
999 case POP_JUMP_IF_TRUE:
1000 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case LOAD_GLOBAL:
1003 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case CONTINUE_LOOP:
1006 return 0;
1007 case SETUP_LOOP:
1008 return 0;
1009 case SETUP_EXCEPT:
1010 case SETUP_FINALLY:
1011 return 6; /* can push 3 values for the new exception
1012 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case LOAD_FAST:
1015 return 1;
1016 case STORE_FAST:
1017 return -1;
1018 case DELETE_FAST:
1019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case RAISE_VARARGS:
1022 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001023#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case CALL_FUNCTION:
1025 return -NARGS(oparg);
1026 case CALL_FUNCTION_VAR:
1027 case CALL_FUNCTION_KW:
1028 return -NARGS(oparg)-1;
1029 case CALL_FUNCTION_VAR_KW:
1030 return -NARGS(oparg)-2;
1031 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001032 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001034 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001035#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case BUILD_SLICE:
1037 if (oparg == 3)
1038 return -2;
1039 else
1040 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_CLOSURE:
1043 return 1;
1044 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001045 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return 1;
1047 case STORE_DEREF:
1048 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001049 case DELETE_DEREF:
1050 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001052 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Larry Hastings3a907972013-11-23 14:49:22 -08001054 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055}
1056
1057/* Add an opcode with no argument.
1058 Returns 0 on failure, 1 on success.
1059*/
1060
1061static int
1062compiler_addop(struct compiler *c, int opcode)
1063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 basicblock *b;
1065 struct instr *i;
1066 int off;
1067 off = compiler_next_instr(c, c->u->u_curblock);
1068 if (off < 0)
1069 return 0;
1070 b = c->u->u_curblock;
1071 i = &b->b_instr[off];
1072 i->i_opcode = opcode;
1073 i->i_hasarg = 0;
1074 if (opcode == RETURN_VALUE)
1075 b->b_return = 1;
1076 compiler_set_lineno(c, off);
1077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
Victor Stinnerf8e32212013-11-19 23:56:34 +01001080static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyObject *t, *v;
1084 Py_ssize_t arg;
1085 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086
Serhiy Storchaka95949422013-08-27 19:40:23 +03001087 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1089 if (PyFloat_Check(o)) {
1090 d = PyFloat_AS_DOUBLE(o);
1091 /* all we need is to make the tuple different in either the 0.0
1092 * or -0.0 case from all others, just to avoid the "coercion".
1093 */
1094 if (d == 0.0 && copysign(1.0, d) < 0.0)
1095 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1096 else
1097 t = PyTuple_Pack(2, o, o->ob_type);
1098 }
1099 else if (PyComplex_Check(o)) {
1100 Py_complex z;
1101 int real_negzero, imag_negzero;
1102 /* For the complex case we must make complex(x, 0.)
1103 different from complex(x, -0.) and complex(0., y)
1104 different from complex(-0., y), for any x and y.
1105 All four complex zeros must be distinguished.*/
1106 z = PyComplex_AsCComplex(o);
1107 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1108 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1109 if (real_negzero && imag_negzero) {
1110 t = PyTuple_Pack(5, o, o->ob_type,
1111 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 else if (imag_negzero) {
1114 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 else if (real_negzero) {
1117 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1118 }
1119 else {
1120 t = PyTuple_Pack(2, o, o->ob_type);
1121 }
1122 }
1123 else {
1124 t = PyTuple_Pack(2, o, o->ob_type);
1125 }
1126 if (t == NULL)
1127 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 v = PyDict_GetItem(dict, t);
1130 if (!v) {
1131 if (PyErr_Occurred())
1132 return -1;
1133 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001134 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (!v) {
1136 Py_DECREF(t);
1137 return -1;
1138 }
1139 if (PyDict_SetItem(dict, t, v) < 0) {
1140 Py_DECREF(t);
1141 Py_DECREF(v);
1142 return -1;
1143 }
1144 Py_DECREF(v);
1145 }
1146 else
1147 arg = PyLong_AsLong(v);
1148 Py_DECREF(t);
1149 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150}
1151
1152static int
1153compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001156 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001158 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 return compiler_addop_i(c, opcode, arg);
1160}
1161
1162static int
1163compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001166 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1168 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001169 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 arg = compiler_add_o(c, dict, mangled);
1171 Py_DECREF(mangled);
1172 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001173 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 return compiler_addop_i(c, opcode, arg);
1175}
1176
1177/* Add an opcode with an integer argument.
1178 Returns 0 on failure, 1 on success.
1179*/
1180
1181static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001182compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 struct instr *i;
1185 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001186
1187 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1188 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001189 assert((-2147483647-1) <= oparg);
1190 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 off = compiler_next_instr(c, c->u->u_curblock);
1193 if (off < 0)
1194 return 0;
1195 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001196 i->i_opcode = opcode;
1197 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 i->i_hasarg = 1;
1199 compiler_set_lineno(c, off);
1200 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201}
1202
1203static int
1204compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 struct instr *i;
1207 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 assert(b != NULL);
1210 off = compiler_next_instr(c, c->u->u_curblock);
1211 if (off < 0)
1212 return 0;
1213 i = &c->u->u_curblock->b_instr[off];
1214 i->i_opcode = opcode;
1215 i->i_target = b;
1216 i->i_hasarg = 1;
1217 if (absolute)
1218 i->i_jabs = 1;
1219 else
1220 i->i_jrel = 1;
1221 compiler_set_lineno(c, off);
1222 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223}
1224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1226 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227 it as the current block. NEXT_BLOCK() also creates an implicit jump
1228 from the current block to the new block.
1229*/
1230
Thomas Wouters89f507f2006-12-13 04:49:30 +00001231/* The returns inside these macros make it impossible to decref objects
1232 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233*/
1234
1235
1236#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (compiler_use_new_block((C)) == NULL) \
1238 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239}
1240
1241#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (compiler_next_block((C)) == NULL) \
1243 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
1246#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (!compiler_addop((C), (OP))) \
1248 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001251#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (!compiler_addop((C), (OP))) { \
1253 compiler_exit_scope(c); \
1254 return 0; \
1255 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001256}
1257
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_addop_i((C), (OP), (O))) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_addop_j((C), (OP), (O), 1)) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_addop_j((C), (OP), (O), 0)) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
1283/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1284 the ASDL name to synthesize the name of the C type and the visit function.
1285*/
1286
1287#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (!compiler_visit_ ## TYPE((C), (V))) \
1289 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290}
1291
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001292#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (!compiler_visit_ ## TYPE((C), (V))) { \
1294 compiler_exit_scope(c); \
1295 return 0; \
1296 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001297}
1298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (!compiler_visit_slice((C), (V), (CTX))) \
1301 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302}
1303
1304#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int _i; \
1306 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1307 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1308 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1309 if (!compiler_visit_ ## TYPE((C), elt)) \
1310 return 0; \
1311 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312}
1313
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001314#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 int _i; \
1316 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1317 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1318 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1319 if (!compiler_visit_ ## TYPE((C), elt)) { \
1320 compiler_exit_scope(c); \
1321 return 0; \
1322 } \
1323 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001324}
1325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326static int
1327compiler_isdocstring(stmt_ty s)
1328{
1329 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 return s->v.Expr.value->kind == Str_kind;
1332}
1333
1334/* Compile a sequence of statements, checking for a docstring. */
1335
1336static int
1337compiler_body(struct compiler *c, asdl_seq *stmts)
1338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 int i = 0;
1340 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (!asdl_seq_LEN(stmts))
1343 return 1;
1344 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001345 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* don't generate docstrings if -OO */
1347 i = 1;
1348 VISIT(c, expr, st->v.Expr.value);
1349 if (!compiler_nameop(c, __doc__, Store))
1350 return 0;
1351 }
1352 for (; i < asdl_seq_LEN(stmts); i++)
1353 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1354 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355}
1356
1357static PyCodeObject *
1358compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyCodeObject *co;
1361 int addNone = 1;
1362 static PyObject *module;
1363 if (!module) {
1364 module = PyUnicode_InternFromString("<module>");
1365 if (!module)
1366 return NULL;
1367 }
1368 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001369 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return NULL;
1371 switch (mod->kind) {
1372 case Module_kind:
1373 if (!compiler_body(c, mod->v.Module.body)) {
1374 compiler_exit_scope(c);
1375 return 0;
1376 }
1377 break;
1378 case Interactive_kind:
1379 c->c_interactive = 1;
1380 VISIT_SEQ_IN_SCOPE(c, stmt,
1381 mod->v.Interactive.body);
1382 break;
1383 case Expression_kind:
1384 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1385 addNone = 0;
1386 break;
1387 case Suite_kind:
1388 PyErr_SetString(PyExc_SystemError,
1389 "suite should not be possible");
1390 return 0;
1391 default:
1392 PyErr_Format(PyExc_SystemError,
1393 "module kind %d should not be possible",
1394 mod->kind);
1395 return 0;
1396 }
1397 co = assemble(c, addNone);
1398 compiler_exit_scope(c);
1399 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001400}
1401
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402/* The test for LOCAL must come before the test for FREE in order to
1403 handle classes where name is both local and free. The local var is
1404 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001405*/
1406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407static int
1408get_ref_type(struct compiler *c, PyObject *name)
1409{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001410 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001411 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1412 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1413 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001414 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (scope == 0) {
1416 char buf[350];
1417 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001418 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001420 PyUnicode_AsUTF8(name),
1421 PyUnicode_AsUTF8(c->u->u_name),
1422 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1423 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1424 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1425 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 );
1427 Py_FatalError(buf);
1428 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431}
1432
1433static int
1434compiler_lookup_arg(PyObject *dict, PyObject *name)
1435{
1436 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001437 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001439 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001441 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001443 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001444 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
1447static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001448compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001450 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001451 if (qualname == NULL)
1452 qualname = co->co_name;
1453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (free == 0) {
1455 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001456 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 ADDOP_I(c, MAKE_FUNCTION, args);
1458 return 1;
1459 }
1460 for (i = 0; i < free; ++i) {
1461 /* Bypass com_addop_varname because it will generate
1462 LOAD_DEREF but LOAD_CLOSURE is needed.
1463 */
1464 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1465 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 /* Special case: If a class contains a method with a
1468 free variable that has the same name as a method,
1469 the name will be considered free *and* local in the
1470 class. It should be handled by the closure, as
1471 well as by the normal name loookup logic.
1472 */
1473 reftype = get_ref_type(c, name);
1474 if (reftype == CELL)
1475 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1476 else /* (reftype == FREE) */
1477 arg = compiler_lookup_arg(c->u->u_freevars, name);
1478 if (arg == -1) {
1479 fprintf(stderr,
1480 "lookup %s in %s %d %d\n"
1481 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001482 PyUnicode_AsUTF8(PyObject_Repr(name)),
1483 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001485 PyUnicode_AsUTF8(co->co_name),
1486 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 Py_FatalError("compiler_make_closure()");
1488 }
1489 ADDOP_I(c, LOAD_CLOSURE, arg);
1490 }
1491 ADDOP_I(c, BUILD_TUPLE, free);
1492 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001493 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 ADDOP_I(c, MAKE_CLOSURE, args);
1495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498static int
1499compiler_decorators(struct compiler *c, asdl_seq* decos)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (!decos)
1504 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1507 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1508 }
1509 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510}
1511
1512static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001513compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 int i, default_count = 0;
1517 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1518 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1519 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1520 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001521 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1522 if (!mangled)
1523 return -1;
1524 ADDOP_O(c, LOAD_CONST, mangled, consts);
1525 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!compiler_visit_expr(c, default_)) {
1527 return -1;
1528 }
1529 default_count++;
1530 }
1531 }
1532 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001533}
1534
1535static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001536compiler_visit_argannotation(struct compiler *c, identifier id,
1537 expr_ty annotation, PyObject *names)
1538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001540 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001542 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001543 if (!mangled)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 return -1;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001545 if (PyList_Append(names, mangled) < 0) {
1546 Py_DECREF(mangled);
1547 return -1;
1548 }
1549 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 }
1551 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001552}
1553
1554static int
1555compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1556 PyObject *names)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 int i, error;
1559 for (i = 0; i < asdl_seq_LEN(args); i++) {
1560 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1561 error = compiler_visit_argannotation(
1562 c,
1563 arg->arg,
1564 arg->annotation,
1565 names);
1566 if (error)
1567 return error;
1568 }
1569 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001570}
1571
1572static int
1573compiler_visit_annotations(struct compiler *c, arguments_ty args,
1574 expr_ty returns)
1575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 /* Push arg annotations and a list of the argument names. Return the #
1577 of items pushed. The expressions are evaluated out-of-order wrt the
1578 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1581 */
1582 static identifier return_str;
1583 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001584 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 names = PyList_New(0);
1586 if (!names)
1587 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (compiler_visit_argannotations(c, args->args, names))
1590 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001591 if (args->vararg && args->vararg->annotation &&
1592 compiler_visit_argannotation(c, args->vararg->arg,
1593 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 goto error;
1595 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1596 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001597 if (args->kwarg && args->kwarg->annotation &&
1598 compiler_visit_argannotation(c, args->kwarg->arg,
1599 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (!return_str) {
1603 return_str = PyUnicode_InternFromString("return");
1604 if (!return_str)
1605 goto error;
1606 }
1607 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1608 goto error;
1609 }
1610
1611 len = PyList_GET_SIZE(names);
1612 if (len > 65534) {
1613 /* len must fit in 16 bits, and len is incremented below */
1614 PyErr_SetString(PyExc_SyntaxError,
1615 "too many annotations");
1616 goto error;
1617 }
1618 if (len) {
1619 /* convert names to a tuple and place on stack */
1620 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001621 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *s = PyTuple_New(len);
1623 if (!s)
1624 goto error;
1625 for (i = 0; i < len; i++) {
1626 elt = PyList_GET_ITEM(names, i);
1627 Py_INCREF(elt);
1628 PyTuple_SET_ITEM(s, i, elt);
1629 }
1630 ADDOP_O(c, LOAD_CONST, s, consts);
1631 Py_DECREF(s);
1632 len++; /* include the just-pushed tuple */
1633 }
1634 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001635
1636 /* We just checked that len <= 65535, see above */
1637 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001638
1639error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 Py_DECREF(names);
1641 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001642}
1643
1644static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645compiler_function(struct compiler *c, stmt_ty s)
1646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001648 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 arguments_ty args = s->v.FunctionDef.args;
1650 expr_ty returns = s->v.FunctionDef.returns;
1651 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1652 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001653 Py_ssize_t i, n, arglength;
1654 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (!compiler_decorators(c, decos))
1660 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001661 if (args->defaults)
1662 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (args->kwonlyargs) {
1664 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1665 args->kw_defaults);
1666 if (res < 0)
1667 return 0;
1668 kw_default_count = res;
1669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 num_annotations = compiler_visit_annotations(c, args, returns);
1671 if (num_annotations < 0)
1672 return 0;
1673 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001674
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001675 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1676 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 s->lineno))
1678 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1681 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001682 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 first_const = st->v.Expr.value->v.Str.s;
1684 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1685 compiler_exit_scope(c);
1686 return 0;
1687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 c->u->u_argcount = asdl_seq_LEN(args->args);
1690 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1691 n = asdl_seq_LEN(s->v.FunctionDef.body);
1692 /* if there was a docstring, we need to skip the first statement */
1693 for (i = docstring; i < n; i++) {
1694 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1695 VISIT_IN_SCOPE(c, stmt, st);
1696 }
1697 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001698 qualname = c->u->u_qualname;
1699 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001701 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001702 Py_XDECREF(qualname);
1703 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001705 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 arglength = asdl_seq_LEN(args->defaults);
1708 arglength |= kw_default_count << 8;
1709 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001710 compiler_make_closure(c, co, arglength, qualname);
1711 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* decorators */
1715 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1716 ADDOP_I(c, CALL_FUNCTION, 1);
1717 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720}
1721
1722static int
1723compiler_class(struct compiler *c, stmt_ty s)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyCodeObject *co;
1726 PyObject *str;
1727 int i;
1728 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (!compiler_decorators(c, decos))
1731 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* ultimately generate code for:
1734 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1735 where:
1736 <func> is a function/closure created from the class body;
1737 it has a single argument (__locals__) where the dict
1738 (or MutableSequence) representing the locals is passed
1739 <name> is the class name
1740 <bases> is the positional arguments and *varargs argument
1741 <keywords> is the keyword arguments and **kwds argument
1742 This borrows from compiler_call.
1743 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001746 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1747 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return 0;
1749 /* this block represents what we do in the new scope */
1750 {
1751 /* use the class name for name mangling */
1752 Py_INCREF(s->v.ClassDef.name);
1753 Py_XDECREF(c->u->u_private);
1754 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 /* load (global) __name__ ... */
1756 str = PyUnicode_InternFromString("__name__");
1757 if (!str || !compiler_nameop(c, str, Load)) {
1758 Py_XDECREF(str);
1759 compiler_exit_scope(c);
1760 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 Py_DECREF(str);
1763 /* ... and store it as __module__ */
1764 str = PyUnicode_InternFromString("__module__");
1765 if (!str || !compiler_nameop(c, str, Store)) {
1766 Py_XDECREF(str);
1767 compiler_exit_scope(c);
1768 return 0;
1769 }
1770 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001771 assert(c->u->u_qualname);
1772 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001773 str = PyUnicode_InternFromString("__qualname__");
1774 if (!str || !compiler_nameop(c, str, Store)) {
1775 Py_XDECREF(str);
1776 compiler_exit_scope(c);
1777 return 0;
1778 }
1779 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* compile the body proper */
1781 if (!compiler_body(c, s->v.ClassDef.body)) {
1782 compiler_exit_scope(c);
1783 return 0;
1784 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001785 if (c->u->u_ste->ste_needs_class_closure) {
1786 /* return the (empty) __class__ cell */
1787 str = PyUnicode_InternFromString("__class__");
1788 if (str == NULL) {
1789 compiler_exit_scope(c);
1790 return 0;
1791 }
1792 i = compiler_lookup_arg(c->u->u_cellvars, str);
1793 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001794 if (i < 0) {
1795 compiler_exit_scope(c);
1796 return 0;
1797 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001798 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* Return the cell where to store __class__ */
1800 ADDOP_I(c, LOAD_CLOSURE, i);
1801 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001802 else {
1803 assert(PyDict_Size(c->u->u_cellvars) == 0);
1804 /* This happens when nobody references the cell. Return None. */
1805 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1808 /* create the code object */
1809 co = assemble(c, 1);
1810 }
1811 /* leave the new scope */
1812 compiler_exit_scope(c);
1813 if (co == NULL)
1814 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 /* 2. load the 'build_class' function */
1817 ADDOP(c, LOAD_BUILD_CLASS);
1818
1819 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001820 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 Py_DECREF(co);
1822
1823 /* 4. load class name */
1824 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1825
1826 /* 5. generate the rest of the code for the call */
1827 if (!compiler_call_helper(c, 2,
1828 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001829 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 return 0;
1831
1832 /* 6. apply decorators */
1833 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1834 ADDOP_I(c, CALL_FUNCTION, 1);
1835 }
1836
1837 /* 7. store into <name> */
1838 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1839 return 0;
1840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841}
1842
1843static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001844compiler_ifexp(struct compiler *c, expr_ty e)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 basicblock *end, *next;
1847
1848 assert(e->kind == IfExp_kind);
1849 end = compiler_new_block(c);
1850 if (end == NULL)
1851 return 0;
1852 next = compiler_new_block(c);
1853 if (next == NULL)
1854 return 0;
1855 VISIT(c, expr, e->v.IfExp.test);
1856 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1857 VISIT(c, expr, e->v.IfExp.body);
1858 ADDOP_JREL(c, JUMP_FORWARD, end);
1859 compiler_use_next_block(c, next);
1860 VISIT(c, expr, e->v.IfExp.orelse);
1861 compiler_use_next_block(c, end);
1862 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001863}
1864
1865static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866compiler_lambda(struct compiler *c, expr_ty e)
1867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001869 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001871 int kw_default_count = 0;
1872 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 arguments_ty args = e->v.Lambda.args;
1874 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (!name) {
1877 name = PyUnicode_InternFromString("<lambda>");
1878 if (!name)
1879 return 0;
1880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001882 if (args->defaults)
1883 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (args->kwonlyargs) {
1885 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1886 args->kw_defaults);
1887 if (res < 0) return 0;
1888 kw_default_count = res;
1889 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001890 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001891 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Make None the first constant, so the lambda can't have a
1895 docstring. */
1896 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1897 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 c->u->u_argcount = asdl_seq_LEN(args->args);
1900 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1901 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1902 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001903 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 }
1905 else {
1906 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001907 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001909 qualname = c->u->u_qualname;
1910 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001912 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 arglength = asdl_seq_LEN(args->defaults);
1916 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001917 compiler_make_closure(c, co, arglength, qualname);
1918 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 Py_DECREF(co);
1920
1921 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922}
1923
1924static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925compiler_if(struct compiler *c, stmt_ty s)
1926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 basicblock *end, *next;
1928 int constant;
1929 assert(s->kind == If_kind);
1930 end = compiler_new_block(c);
1931 if (end == NULL)
1932 return 0;
1933
Georg Brandl8334fd92010-12-04 10:26:46 +00001934 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* constant = 0: "if 0"
1936 * constant = 1: "if 1", "if 2", ...
1937 * constant = -1: rest */
1938 if (constant == 0) {
1939 if (s->v.If.orelse)
1940 VISIT_SEQ(c, stmt, s->v.If.orelse);
1941 } else if (constant == 1) {
1942 VISIT_SEQ(c, stmt, s->v.If.body);
1943 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001944 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 next = compiler_new_block(c);
1946 if (next == NULL)
1947 return 0;
1948 }
1949 else
1950 next = end;
1951 VISIT(c, expr, s->v.If.test);
1952 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1953 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001954 if (asdl_seq_LEN(s->v.If.orelse)) {
1955 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 compiler_use_next_block(c, next);
1957 VISIT_SEQ(c, stmt, s->v.If.orelse);
1958 }
1959 }
1960 compiler_use_next_block(c, end);
1961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
1965compiler_for(struct compiler *c, stmt_ty s)
1966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 start = compiler_new_block(c);
1970 cleanup = compiler_new_block(c);
1971 end = compiler_new_block(c);
1972 if (start == NULL || end == NULL || cleanup == NULL)
1973 return 0;
1974 ADDOP_JREL(c, SETUP_LOOP, end);
1975 if (!compiler_push_fblock(c, LOOP, start))
1976 return 0;
1977 VISIT(c, expr, s->v.For.iter);
1978 ADDOP(c, GET_ITER);
1979 compiler_use_next_block(c, start);
1980 ADDOP_JREL(c, FOR_ITER, cleanup);
1981 VISIT(c, expr, s->v.For.target);
1982 VISIT_SEQ(c, stmt, s->v.For.body);
1983 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1984 compiler_use_next_block(c, cleanup);
1985 ADDOP(c, POP_BLOCK);
1986 compiler_pop_fblock(c, LOOP, start);
1987 VISIT_SEQ(c, stmt, s->v.For.orelse);
1988 compiler_use_next_block(c, end);
1989 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990}
1991
1992static int
1993compiler_while(struct compiler *c, stmt_ty s)
1994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001996 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (constant == 0) {
1999 if (s->v.While.orelse)
2000 VISIT_SEQ(c, stmt, s->v.While.orelse);
2001 return 1;
2002 }
2003 loop = compiler_new_block(c);
2004 end = compiler_new_block(c);
2005 if (constant == -1) {
2006 anchor = compiler_new_block(c);
2007 if (anchor == NULL)
2008 return 0;
2009 }
2010 if (loop == NULL || end == NULL)
2011 return 0;
2012 if (s->v.While.orelse) {
2013 orelse = compiler_new_block(c);
2014 if (orelse == NULL)
2015 return 0;
2016 }
2017 else
2018 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 ADDOP_JREL(c, SETUP_LOOP, end);
2021 compiler_use_next_block(c, loop);
2022 if (!compiler_push_fblock(c, LOOP, loop))
2023 return 0;
2024 if (constant == -1) {
2025 VISIT(c, expr, s->v.While.test);
2026 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2027 }
2028 VISIT_SEQ(c, stmt, s->v.While.body);
2029 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* XXX should the two POP instructions be in a separate block
2032 if there is no else clause ?
2033 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002035 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002037 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 compiler_pop_fblock(c, LOOP, loop);
2039 if (orelse != NULL) /* what if orelse is just pass? */
2040 VISIT_SEQ(c, stmt, s->v.While.orelse);
2041 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044}
2045
2046static int
2047compiler_continue(struct compiler *c)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2050 static const char IN_FINALLY_ERROR_MSG[] =
2051 "'continue' not supported inside 'finally' clause";
2052 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (!c->u->u_nfblocks)
2055 return compiler_error(c, LOOP_ERROR_MSG);
2056 i = c->u->u_nfblocks - 1;
2057 switch (c->u->u_fblock[i].fb_type) {
2058 case LOOP:
2059 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2060 break;
2061 case EXCEPT:
2062 case FINALLY_TRY:
2063 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2064 /* Prevent continue anywhere under a finally
2065 even if hidden in a sub-try or except. */
2066 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2067 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2068 }
2069 if (i == -1)
2070 return compiler_error(c, LOOP_ERROR_MSG);
2071 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2072 break;
2073 case FINALLY_END:
2074 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2075 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078}
2079
2080/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081
2082 SETUP_FINALLY L
2083 <code for body>
2084 POP_BLOCK
2085 LOAD_CONST <None>
2086 L: <code for finalbody>
2087 END_FINALLY
2088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 The special instructions use the block stack. Each block
2090 stack entry contains the instruction that created it (here
2091 SETUP_FINALLY), the level of the value stack at the time the
2092 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 Pushes the current value stack level and the label
2096 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Pops en entry from the block stack, and pops the value
2099 stack until its level is the same as indicated on the
2100 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 Pops a variable number of entries from the *value* stack
2103 and re-raises the exception they specify. The number of
2104 entries popped depends on the (pseudo) exception type.
2105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 The block stack is unwound when an exception is raised:
2107 when a SETUP_FINALLY entry is found, the exception is pushed
2108 onto the value stack (and the exception condition is cleared),
2109 and the interpreter jumps to the label gotten from the block
2110 stack.
2111*/
2112
2113static int
2114compiler_try_finally(struct compiler *c, stmt_ty s)
2115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 basicblock *body, *end;
2117 body = compiler_new_block(c);
2118 end = compiler_new_block(c);
2119 if (body == NULL || end == NULL)
2120 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 ADDOP_JREL(c, SETUP_FINALLY, end);
2123 compiler_use_next_block(c, body);
2124 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2125 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002126 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2127 if (!compiler_try_except(c, s))
2128 return 0;
2129 }
2130 else {
2131 VISIT_SEQ(c, stmt, s->v.Try.body);
2132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 ADDOP(c, POP_BLOCK);
2134 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2137 compiler_use_next_block(c, end);
2138 if (!compiler_push_fblock(c, FINALLY_END, end))
2139 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002140 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 ADDOP(c, END_FINALLY);
2142 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145}
2146
2147/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002148 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 (The contents of the value stack is shown in [], with the top
2150 at the right; 'tb' is trace-back info, 'val' the exception's
2151 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152
2153 Value stack Label Instruction Argument
2154 [] SETUP_EXCEPT L1
2155 [] <code for S>
2156 [] POP_BLOCK
2157 [] JUMP_FORWARD L0
2158
2159 [tb, val, exc] L1: DUP )
2160 [tb, val, exc, exc] <evaluate E1> )
2161 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2162 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2163 [tb, val, exc] POP
2164 [tb, val] <assign to V1> (or POP if no V1)
2165 [tb] POP
2166 [] <code for S1>
2167 JUMP_FORWARD L0
2168
2169 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 .............................etc.......................
2171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2173
2174 [] L0: <next statement>
2175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 Of course, parts are not generated if Vi or Ei is not present.
2177*/
2178static int
2179compiler_try_except(struct compiler *c, stmt_ty s)
2180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002182 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 body = compiler_new_block(c);
2185 except = compiler_new_block(c);
2186 orelse = compiler_new_block(c);
2187 end = compiler_new_block(c);
2188 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2189 return 0;
2190 ADDOP_JREL(c, SETUP_EXCEPT, except);
2191 compiler_use_next_block(c, body);
2192 if (!compiler_push_fblock(c, EXCEPT, body))
2193 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002194 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 ADDOP(c, POP_BLOCK);
2196 compiler_pop_fblock(c, EXCEPT, body);
2197 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002198 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 compiler_use_next_block(c, except);
2200 for (i = 0; i < n; i++) {
2201 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002202 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (!handler->v.ExceptHandler.type && i < n-1)
2204 return compiler_error(c, "default 'except:' must be last");
2205 c->u->u_lineno_set = 0;
2206 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002207 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 except = compiler_new_block(c);
2209 if (except == NULL)
2210 return 0;
2211 if (handler->v.ExceptHandler.type) {
2212 ADDOP(c, DUP_TOP);
2213 VISIT(c, expr, handler->v.ExceptHandler.type);
2214 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2215 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2216 }
2217 ADDOP(c, POP_TOP);
2218 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002219 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002220
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002221 cleanup_end = compiler_new_block(c);
2222 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002223 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002224 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002225
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002226 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2227 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 /*
2230 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002231 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002232 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002233 try:
2234 # body
2235 finally:
2236 name = None
2237 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002238 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002240 /* second try: */
2241 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2242 compiler_use_next_block(c, cleanup_body);
2243 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2244 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002246 /* second # body */
2247 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2248 ADDOP(c, POP_BLOCK);
2249 ADDOP(c, POP_EXCEPT);
2250 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002252 /* finally: */
2253 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2254 compiler_use_next_block(c, cleanup_end);
2255 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2256 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002258 /* name = None */
2259 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2260 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002262 /* del name */
2263 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002265 ADDOP(c, END_FINALLY);
2266 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 }
2268 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002269 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002271 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002272 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002273 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274
Guido van Rossumb940e112007-01-10 16:19:56 +00002275 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002276 ADDOP(c, POP_TOP);
2277 compiler_use_next_block(c, cleanup_body);
2278 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2279 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002281 ADDOP(c, POP_EXCEPT);
2282 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 }
2284 ADDOP_JREL(c, JUMP_FORWARD, end);
2285 compiler_use_next_block(c, except);
2286 }
2287 ADDOP(c, END_FINALLY);
2288 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002289 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_use_next_block(c, end);
2291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292}
2293
2294static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002295compiler_try(struct compiler *c, stmt_ty s) {
2296 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2297 return compiler_try_finally(c, s);
2298 else
2299 return compiler_try_except(c, s);
2300}
2301
2302
2303static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304compiler_import_as(struct compiler *c, identifier name, identifier asname)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* The IMPORT_NAME opcode was already generated. This function
2307 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 If there is a dot in name, we need to split it and emit a
2310 LOAD_ATTR for each name.
2311 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002312 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2313 PyUnicode_GET_LENGTH(name), 1);
2314 if (dot == -2)
2315 return -1;
2316 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002318 Py_ssize_t pos = dot + 1;
2319 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002321 dot = PyUnicode_FindChar(name, '.', pos,
2322 PyUnicode_GET_LENGTH(name), 1);
2323 if (dot == -2)
2324 return -1;
2325 attr = PyUnicode_Substring(name, pos,
2326 (dot != -1) ? dot :
2327 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (!attr)
2329 return -1;
2330 ADDOP_O(c, LOAD_ATTR, attr, names);
2331 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002332 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 }
2334 }
2335 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336}
2337
2338static int
2339compiler_import(struct compiler *c, stmt_ty s)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* The Import node stores a module name like a.b.c as a single
2342 string. This is convenient for all cases except
2343 import a.b.c as d
2344 where we need to parse that string to extract the individual
2345 module names.
2346 XXX Perhaps change the representation to make this case simpler?
2347 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002348 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 for (i = 0; i < n; i++) {
2351 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2352 int r;
2353 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 level = PyLong_FromLong(0);
2356 if (level == NULL)
2357 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 ADDOP_O(c, LOAD_CONST, level, consts);
2360 Py_DECREF(level);
2361 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2362 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if (alias->asname) {
2365 r = compiler_import_as(c, alias->name, alias->asname);
2366 if (!r)
2367 return r;
2368 }
2369 else {
2370 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 Py_ssize_t dot = PyUnicode_FindChar(
2372 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002373 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002375 if (tmp == NULL)
2376 return 0;
2377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Py_DECREF(tmp);
2381 }
2382 if (!r)
2383 return r;
2384 }
2385 }
2386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387}
2388
2389static int
2390compiler_from_import(struct compiler *c, stmt_ty s)
2391{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002392 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 PyObject *names = PyTuple_New(n);
2395 PyObject *level;
2396 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 if (!empty_string) {
2399 empty_string = PyUnicode_FromString("");
2400 if (!empty_string)
2401 return 0;
2402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (!names)
2405 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 level = PyLong_FromLong(s->v.ImportFrom.level);
2408 if (!level) {
2409 Py_DECREF(names);
2410 return 0;
2411 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* build up the names */
2414 for (i = 0; i < n; i++) {
2415 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2416 Py_INCREF(alias->name);
2417 PyTuple_SET_ITEM(names, i, alias->name);
2418 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2421 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2422 Py_DECREF(level);
2423 Py_DECREF(names);
2424 return compiler_error(c, "from __future__ imports must occur "
2425 "at the beginning of the file");
2426 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 ADDOP_O(c, LOAD_CONST, level, consts);
2429 Py_DECREF(level);
2430 ADDOP_O(c, LOAD_CONST, names, consts);
2431 Py_DECREF(names);
2432 if (s->v.ImportFrom.module) {
2433 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2434 }
2435 else {
2436 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2437 }
2438 for (i = 0; i < n; i++) {
2439 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2440 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 assert(n == 1);
2444 ADDOP(c, IMPORT_STAR);
2445 return 1;
2446 }
2447
2448 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2449 store_name = alias->name;
2450 if (alias->asname)
2451 store_name = alias->asname;
2452
2453 if (!compiler_nameop(c, store_name, Store)) {
2454 Py_DECREF(names);
2455 return 0;
2456 }
2457 }
2458 /* remove imported module */
2459 ADDOP(c, POP_TOP);
2460 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461}
2462
2463static int
2464compiler_assert(struct compiler *c, stmt_ty s)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 static PyObject *assertion_error = NULL;
2467 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002468 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469
Georg Brandl8334fd92010-12-04 10:26:46 +00002470 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return 1;
2472 if (assertion_error == NULL) {
2473 assertion_error = PyUnicode_InternFromString("AssertionError");
2474 if (assertion_error == NULL)
2475 return 0;
2476 }
2477 if (s->v.Assert.test->kind == Tuple_kind &&
2478 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002479 msg = PyUnicode_FromString("assertion is always true, "
2480 "perhaps remove parentheses?");
2481 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002483 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2484 c->c_filename, c->u->u_lineno,
2485 NULL, NULL) == -1) {
2486 Py_DECREF(msg);
2487 return 0;
2488 }
2489 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 }
2491 VISIT(c, expr, s->v.Assert.test);
2492 end = compiler_new_block(c);
2493 if (end == NULL)
2494 return 0;
2495 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2496 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2497 if (s->v.Assert.msg) {
2498 VISIT(c, expr, s->v.Assert.msg);
2499 ADDOP_I(c, CALL_FUNCTION, 1);
2500 }
2501 ADDOP_I(c, RAISE_VARARGS, 1);
2502 compiler_use_next_block(c, end);
2503 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504}
2505
2506static int
2507compiler_visit_stmt(struct compiler *c, stmt_ty s)
2508{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002509 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 /* Always assign a lineno to the next instruction for a stmt. */
2512 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002513 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 switch (s->kind) {
2517 case FunctionDef_kind:
2518 return compiler_function(c, s);
2519 case ClassDef_kind:
2520 return compiler_class(c, s);
2521 case Return_kind:
2522 if (c->u->u_ste->ste_type != FunctionBlock)
2523 return compiler_error(c, "'return' outside function");
2524 if (s->v.Return.value) {
2525 VISIT(c, expr, s->v.Return.value);
2526 }
2527 else
2528 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2529 ADDOP(c, RETURN_VALUE);
2530 break;
2531 case Delete_kind:
2532 VISIT_SEQ(c, expr, s->v.Delete.targets)
2533 break;
2534 case Assign_kind:
2535 n = asdl_seq_LEN(s->v.Assign.targets);
2536 VISIT(c, expr, s->v.Assign.value);
2537 for (i = 0; i < n; i++) {
2538 if (i < n - 1)
2539 ADDOP(c, DUP_TOP);
2540 VISIT(c, expr,
2541 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2542 }
2543 break;
2544 case AugAssign_kind:
2545 return compiler_augassign(c, s);
2546 case For_kind:
2547 return compiler_for(c, s);
2548 case While_kind:
2549 return compiler_while(c, s);
2550 case If_kind:
2551 return compiler_if(c, s);
2552 case Raise_kind:
2553 n = 0;
2554 if (s->v.Raise.exc) {
2555 VISIT(c, expr, s->v.Raise.exc);
2556 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002557 if (s->v.Raise.cause) {
2558 VISIT(c, expr, s->v.Raise.cause);
2559 n++;
2560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002562 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002564 case Try_kind:
2565 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 case Assert_kind:
2567 return compiler_assert(c, s);
2568 case Import_kind:
2569 return compiler_import(c, s);
2570 case ImportFrom_kind:
2571 return compiler_from_import(c, s);
2572 case Global_kind:
2573 case Nonlocal_kind:
2574 break;
2575 case Expr_kind:
2576 if (c->c_interactive && c->c_nestlevel <= 1) {
2577 VISIT(c, expr, s->v.Expr.value);
2578 ADDOP(c, PRINT_EXPR);
2579 }
2580 else if (s->v.Expr.value->kind != Str_kind &&
2581 s->v.Expr.value->kind != Num_kind) {
2582 VISIT(c, expr, s->v.Expr.value);
2583 ADDOP(c, POP_TOP);
2584 }
2585 break;
2586 case Pass_kind:
2587 break;
2588 case Break_kind:
2589 if (!compiler_in_loop(c))
2590 return compiler_error(c, "'break' outside loop");
2591 ADDOP(c, BREAK_LOOP);
2592 break;
2593 case Continue_kind:
2594 return compiler_continue(c);
2595 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002596 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 }
2598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599}
2600
2601static int
2602unaryop(unaryop_ty op)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 switch (op) {
2605 case Invert:
2606 return UNARY_INVERT;
2607 case Not:
2608 return UNARY_NOT;
2609 case UAdd:
2610 return UNARY_POSITIVE;
2611 case USub:
2612 return UNARY_NEGATIVE;
2613 default:
2614 PyErr_Format(PyExc_SystemError,
2615 "unary op %d should not be possible", op);
2616 return 0;
2617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618}
2619
2620static int
2621binop(struct compiler *c, operator_ty op)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 switch (op) {
2624 case Add:
2625 return BINARY_ADD;
2626 case Sub:
2627 return BINARY_SUBTRACT;
2628 case Mult:
2629 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002630 case MatMult:
2631 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 case Div:
2633 return BINARY_TRUE_DIVIDE;
2634 case Mod:
2635 return BINARY_MODULO;
2636 case Pow:
2637 return BINARY_POWER;
2638 case LShift:
2639 return BINARY_LSHIFT;
2640 case RShift:
2641 return BINARY_RSHIFT;
2642 case BitOr:
2643 return BINARY_OR;
2644 case BitXor:
2645 return BINARY_XOR;
2646 case BitAnd:
2647 return BINARY_AND;
2648 case FloorDiv:
2649 return BINARY_FLOOR_DIVIDE;
2650 default:
2651 PyErr_Format(PyExc_SystemError,
2652 "binary op %d should not be possible", op);
2653 return 0;
2654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655}
2656
2657static int
2658cmpop(cmpop_ty op)
2659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 switch (op) {
2661 case Eq:
2662 return PyCmp_EQ;
2663 case NotEq:
2664 return PyCmp_NE;
2665 case Lt:
2666 return PyCmp_LT;
2667 case LtE:
2668 return PyCmp_LE;
2669 case Gt:
2670 return PyCmp_GT;
2671 case GtE:
2672 return PyCmp_GE;
2673 case Is:
2674 return PyCmp_IS;
2675 case IsNot:
2676 return PyCmp_IS_NOT;
2677 case In:
2678 return PyCmp_IN;
2679 case NotIn:
2680 return PyCmp_NOT_IN;
2681 default:
2682 return PyCmp_BAD;
2683 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684}
2685
2686static int
2687inplace_binop(struct compiler *c, operator_ty op)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 switch (op) {
2690 case Add:
2691 return INPLACE_ADD;
2692 case Sub:
2693 return INPLACE_SUBTRACT;
2694 case Mult:
2695 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002696 case MatMult:
2697 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 case Div:
2699 return INPLACE_TRUE_DIVIDE;
2700 case Mod:
2701 return INPLACE_MODULO;
2702 case Pow:
2703 return INPLACE_POWER;
2704 case LShift:
2705 return INPLACE_LSHIFT;
2706 case RShift:
2707 return INPLACE_RSHIFT;
2708 case BitOr:
2709 return INPLACE_OR;
2710 case BitXor:
2711 return INPLACE_XOR;
2712 case BitAnd:
2713 return INPLACE_AND;
2714 case FloorDiv:
2715 return INPLACE_FLOOR_DIVIDE;
2716 default:
2717 PyErr_Format(PyExc_SystemError,
2718 "inplace binary op %d should not be possible", op);
2719 return 0;
2720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721}
2722
2723static int
2724compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2725{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002726 int op, scope;
2727 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 PyObject *dict = c->u->u_names;
2731 PyObject *mangled;
2732 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 mangled = _Py_Mangle(c->u->u_private, name);
2735 if (!mangled)
2736 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002737
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002738 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2739 PyUnicode_CompareWithASCIIString(name, "True") &&
2740 PyUnicode_CompareWithASCIIString(name, "False"));
2741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 op = 0;
2743 optype = OP_NAME;
2744 scope = PyST_GetScope(c->u->u_ste, mangled);
2745 switch (scope) {
2746 case FREE:
2747 dict = c->u->u_freevars;
2748 optype = OP_DEREF;
2749 break;
2750 case CELL:
2751 dict = c->u->u_cellvars;
2752 optype = OP_DEREF;
2753 break;
2754 case LOCAL:
2755 if (c->u->u_ste->ste_type == FunctionBlock)
2756 optype = OP_FAST;
2757 break;
2758 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002759 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 optype = OP_GLOBAL;
2761 break;
2762 case GLOBAL_EXPLICIT:
2763 optype = OP_GLOBAL;
2764 break;
2765 default:
2766 /* scope can be 0 */
2767 break;
2768 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 switch (optype) {
2774 case OP_DEREF:
2775 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002776 case Load:
2777 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2778 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 case Store: op = STORE_DEREF; break;
2780 case AugLoad:
2781 case AugStore:
2782 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002783 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 case Param:
2785 default:
2786 PyErr_SetString(PyExc_SystemError,
2787 "param invalid for deref variable");
2788 return 0;
2789 }
2790 break;
2791 case OP_FAST:
2792 switch (ctx) {
2793 case Load: op = LOAD_FAST; break;
2794 case Store: op = STORE_FAST; break;
2795 case Del: op = DELETE_FAST; break;
2796 case AugLoad:
2797 case AugStore:
2798 break;
2799 case Param:
2800 default:
2801 PyErr_SetString(PyExc_SystemError,
2802 "param invalid for local variable");
2803 return 0;
2804 }
2805 ADDOP_O(c, op, mangled, varnames);
2806 Py_DECREF(mangled);
2807 return 1;
2808 case OP_GLOBAL:
2809 switch (ctx) {
2810 case Load: op = LOAD_GLOBAL; break;
2811 case Store: op = STORE_GLOBAL; break;
2812 case Del: op = DELETE_GLOBAL; break;
2813 case AugLoad:
2814 case AugStore:
2815 break;
2816 case Param:
2817 default:
2818 PyErr_SetString(PyExc_SystemError,
2819 "param invalid for global variable");
2820 return 0;
2821 }
2822 break;
2823 case OP_NAME:
2824 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002825 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 case Store: op = STORE_NAME; break;
2827 case Del: op = DELETE_NAME; break;
2828 case AugLoad:
2829 case AugStore:
2830 break;
2831 case Param:
2832 default:
2833 PyErr_SetString(PyExc_SystemError,
2834 "param invalid for name variable");
2835 return 0;
2836 }
2837 break;
2838 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 assert(op);
2841 arg = compiler_add_o(c, dict, mangled);
2842 Py_DECREF(mangled);
2843 if (arg < 0)
2844 return 0;
2845 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846}
2847
2848static int
2849compiler_boolop(struct compiler *c, expr_ty e)
2850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002852 int jumpi;
2853 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 assert(e->kind == BoolOp_kind);
2857 if (e->v.BoolOp.op == And)
2858 jumpi = JUMP_IF_FALSE_OR_POP;
2859 else
2860 jumpi = JUMP_IF_TRUE_OR_POP;
2861 end = compiler_new_block(c);
2862 if (end == NULL)
2863 return 0;
2864 s = e->v.BoolOp.values;
2865 n = asdl_seq_LEN(s) - 1;
2866 assert(n >= 0);
2867 for (i = 0; i < n; ++i) {
2868 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2869 ADDOP_JABS(c, jumpi, end);
2870 }
2871 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2872 compiler_use_next_block(c, end);
2873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
2875
2876static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002877starunpack_helper(struct compiler *c, asdl_seq *elts,
2878 int single_op, int inner_op, int outer_op)
2879{
2880 Py_ssize_t n = asdl_seq_LEN(elts);
2881 Py_ssize_t i, nsubitems = 0, nseen = 0;
2882 for (i = 0; i < n; i++) {
2883 expr_ty elt = asdl_seq_GET(elts, i);
2884 if (elt->kind == Starred_kind) {
2885 if (nseen) {
2886 ADDOP_I(c, inner_op, nseen);
2887 nseen = 0;
2888 nsubitems++;
2889 }
2890 VISIT(c, expr, elt->v.Starred.value);
2891 nsubitems++;
2892 }
2893 else {
2894 VISIT(c, expr, elt);
2895 nseen++;
2896 }
2897 }
2898 if (nsubitems) {
2899 if (nseen) {
2900 ADDOP_I(c, inner_op, nseen);
2901 nsubitems++;
2902 }
2903 ADDOP_I(c, outer_op, nsubitems);
2904 }
2905 else
2906 ADDOP_I(c, single_op, nseen);
2907 return 1;
2908}
2909
2910static int
2911assignment_helper(struct compiler *c, asdl_seq *elts)
2912{
2913 Py_ssize_t n = asdl_seq_LEN(elts);
2914 Py_ssize_t i;
2915 int seen_star = 0;
2916 for (i = 0; i < n; i++) {
2917 expr_ty elt = asdl_seq_GET(elts, i);
2918 if (elt->kind == Starred_kind && !seen_star) {
2919 if ((i >= (1 << 8)) ||
2920 (n-i-1 >= (INT_MAX >> 8)))
2921 return compiler_error(c,
2922 "too many expressions in "
2923 "star-unpacking assignment");
2924 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2925 seen_star = 1;
2926 asdl_seq_SET(elts, i, elt->v.Starred.value);
2927 }
2928 else if (elt->kind == Starred_kind) {
2929 return compiler_error(c,
2930 "two starred expressions in assignment");
2931 }
2932 }
2933 if (!seen_star) {
2934 ADDOP_I(c, UNPACK_SEQUENCE, n);
2935 }
2936 VISIT_SEQ(c, expr, elts);
2937 return 1;
2938}
2939
2940static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941compiler_list(struct compiler *c, expr_ty e)
2942{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002943 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002945 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002947 else if (e->v.List.ctx == Load) {
2948 return starunpack_helper(c, elts,
2949 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002951 else
2952 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954}
2955
2956static int
2957compiler_tuple(struct compiler *c, expr_ty e)
2958{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002959 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002961 return assignment_helper(c, elts);
2962 }
2963 else if (e->v.Tuple.ctx == Load) {
2964 return starunpack_helper(c, elts,
2965 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
2966 }
2967 else
2968 VISIT_SEQ(c, expr, elts);
2969 return 1;
2970}
2971
2972static int
2973compiler_set(struct compiler *c, expr_ty e)
2974{
2975 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
2976 BUILD_SET, BUILD_SET_UNPACK);
2977}
2978
2979static int
2980compiler_dict(struct compiler *c, expr_ty e)
2981{
2982 Py_ssize_t i, n, containers, elements;
2983 int is_unpacking = 0;
2984 n = asdl_seq_LEN(e->v.Dict.values);
2985 containers = 0;
2986 elements = 0;
2987 for (i = 0; i < n; i++) {
2988 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
2989 if (elements == 0xFFFF || (elements && is_unpacking)) {
2990 ADDOP_I(c, BUILD_MAP, elements);
2991 containers++;
2992 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002994 if (is_unpacking) {
2995 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
2996 containers++;
2997 }
2998 else {
2999 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3000 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3001 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 }
3003 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003004 if (elements || containers == 0) {
3005 ADDOP_I(c, BUILD_MAP, elements);
3006 containers++;
3007 }
3008 /* If there is more than one dict, they need to be merged into a new
3009 * dict. If there is one dict and it's an unpacking, then it needs
3010 * to be copied into a new dict." */
3011 while (containers > 1 || is_unpacking) {
3012 int oparg = containers < 255 ? containers : 255;
3013 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3014 containers -= (oparg - 1);
3015 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 }
3017 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018}
3019
3020static int
3021compiler_compare(struct compiler *c, expr_ty e)
3022{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003023 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3027 VISIT(c, expr, e->v.Compare.left);
3028 n = asdl_seq_LEN(e->v.Compare.ops);
3029 assert(n > 0);
3030 if (n > 1) {
3031 cleanup = compiler_new_block(c);
3032 if (cleanup == NULL)
3033 return 0;
3034 VISIT(c, expr,
3035 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3036 }
3037 for (i = 1; i < n; i++) {
3038 ADDOP(c, DUP_TOP);
3039 ADDOP(c, ROT_THREE);
3040 ADDOP_I(c, COMPARE_OP,
3041 cmpop((cmpop_ty)(asdl_seq_GET(
3042 e->v.Compare.ops, i - 1))));
3043 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3044 NEXT_BLOCK(c);
3045 if (i < (n - 1))
3046 VISIT(c, expr,
3047 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3048 }
3049 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3050 ADDOP_I(c, COMPARE_OP,
3051 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3052 if (n > 1) {
3053 basicblock *end = compiler_new_block(c);
3054 if (end == NULL)
3055 return 0;
3056 ADDOP_JREL(c, JUMP_FORWARD, end);
3057 compiler_use_next_block(c, cleanup);
3058 ADDOP(c, ROT_TWO);
3059 ADDOP(c, POP_TOP);
3060 compiler_use_next_block(c, end);
3061 }
3062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063}
3064
3065static int
3066compiler_call(struct compiler *c, expr_ty e)
3067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 VISIT(c, expr, e->v.Call.func);
3069 return compiler_call_helper(c, 0,
3070 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003071 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003072}
3073
3074/* shared code between compiler_call and compiler_class */
3075static int
3076compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003077 Py_ssize_t n, /* Args already pushed */
3078 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003079 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003082 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003083
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003084 /* the number of tuples and dictionaries on the stack */
3085 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3086
3087 nkw = 0;
3088 nseen = 0; /* the number of positional arguments on the stack */
3089 nelts = asdl_seq_LEN(args);
3090 for (i = 0; i < nelts; i++) {
3091 expr_ty elt = asdl_seq_GET(args, i);
3092 if (elt->kind == Starred_kind) {
3093 /* A star-arg. If we've seen positional arguments,
3094 pack the positional arguments into a
3095 tuple. */
3096 if (nseen) {
3097 ADDOP_I(c, BUILD_TUPLE, nseen);
3098 nseen = 0;
3099 nsubargs++;
3100 }
3101 VISIT(c, expr, elt->v.Starred.value);
3102 nsubargs++;
3103 }
3104 else if (nsubargs) {
3105 /* We've seen star-args already, so we
3106 count towards items-to-pack-into-tuple. */
3107 VISIT(c, expr, elt);
3108 nseen++;
3109 }
3110 else {
3111 /* Positional arguments before star-arguments
3112 are left on the stack. */
3113 VISIT(c, expr, elt);
3114 n++;
3115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003117 if (nseen) {
3118 /* Pack up any trailing positional arguments. */
3119 ADDOP_I(c, BUILD_TUPLE, nseen);
3120 nsubargs++;
3121 }
3122 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003124 if (nsubargs > 1) {
3125 /* If we ended up with more than one stararg, we need
3126 to concatenate them into a single sequence. */
3127 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003130
3131 /* Same dance again for keyword arguments */
3132 nseen = 0; /* the number of keyword arguments on the stack following */
3133 nelts = asdl_seq_LEN(keywords);
3134 for (i = 0; i < nelts; i++) {
3135 keyword_ty kw = asdl_seq_GET(keywords, i);
3136 if (kw->arg == NULL) {
3137 /* A keyword argument unpacking. */
3138 if (nseen) {
3139 ADDOP_I(c, BUILD_MAP, nseen);
3140 nseen = 0;
3141 nsubkwargs++;
3142 }
3143 VISIT(c, expr, kw->value);
3144 nsubkwargs++;
3145 }
3146 else if (nsubkwargs) {
3147 /* A keyword argument and we already have a dict. */
3148 VISIT(c, expr, kw->value);
3149 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3150 nseen++;
3151 }
3152 else {
3153 /* keyword argument */
3154 VISIT(c, keyword, kw)
3155 nkw++;
3156 }
3157 }
3158 if (nseen) {
3159 /* Pack up any trailing keyword arguments. */
3160 ADDOP_I(c, BUILD_MAP, nseen);
3161 nsubkwargs++;
3162 }
3163 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003165 if (nsubkwargs > 1) {
3166 /* Pack it all up */
3167 int function_pos = n + (code & 1) + nkw + 1;
3168 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3169 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003171 assert(n < 1<<8);
3172 assert(nkw < 1<<24);
3173 n |= nkw << 8;
3174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 switch (code) {
3176 case 0:
3177 ADDOP_I(c, CALL_FUNCTION, n);
3178 break;
3179 case 1:
3180 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3181 break;
3182 case 2:
3183 ADDOP_I(c, CALL_FUNCTION_KW, n);
3184 break;
3185 case 3:
3186 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3187 break;
3188 }
3189 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190}
3191
Nick Coghlan650f0d02007-04-15 12:05:43 +00003192
3193/* List and set comprehensions and generator expressions work by creating a
3194 nested function to perform the actual iteration. This means that the
3195 iteration variables don't leak into the current scope.
3196 The defined function is called immediately following its definition, with the
3197 result of that call being the result of the expression.
3198 The LC/SC version returns the populated container, while the GE version is
3199 flagged in symtable.c as a generator, so it returns the generator object
3200 when the function is called.
3201 This code *knows* that the loop cannot contain break, continue, or return,
3202 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3203
3204 Possible cleanups:
3205 - iterate over the generator sequence instead of using recursion
3206*/
3207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209compiler_comprehension_generator(struct compiler *c,
3210 asdl_seq *generators, int gen_index,
3211 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 /* generate code for the iterator, then each of the ifs,
3214 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 comprehension_ty gen;
3217 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003218 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 start = compiler_new_block(c);
3221 skip = compiler_new_block(c);
3222 if_cleanup = compiler_new_block(c);
3223 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3226 anchor == NULL)
3227 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 if (gen_index == 0) {
3232 /* Receive outermost iter as an implicit argument */
3233 c->u->u_argcount = 1;
3234 ADDOP_I(c, LOAD_FAST, 0);
3235 }
3236 else {
3237 /* Sub-iter - calculate on the fly */
3238 VISIT(c, expr, gen->iter);
3239 ADDOP(c, GET_ITER);
3240 }
3241 compiler_use_next_block(c, start);
3242 ADDOP_JREL(c, FOR_ITER, anchor);
3243 NEXT_BLOCK(c);
3244 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 /* XXX this needs to be cleaned up...a lot! */
3247 n = asdl_seq_LEN(gen->ifs);
3248 for (i = 0; i < n; i++) {
3249 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3250 VISIT(c, expr, e);
3251 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3252 NEXT_BLOCK(c);
3253 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 if (++gen_index < asdl_seq_LEN(generators))
3256 if (!compiler_comprehension_generator(c,
3257 generators, gen_index,
3258 elt, val, type))
3259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* only append after the last for generator */
3262 if (gen_index >= asdl_seq_LEN(generators)) {
3263 /* comprehension specific code */
3264 switch (type) {
3265 case COMP_GENEXP:
3266 VISIT(c, expr, elt);
3267 ADDOP(c, YIELD_VALUE);
3268 ADDOP(c, POP_TOP);
3269 break;
3270 case COMP_LISTCOMP:
3271 VISIT(c, expr, elt);
3272 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3273 break;
3274 case COMP_SETCOMP:
3275 VISIT(c, expr, elt);
3276 ADDOP_I(c, SET_ADD, gen_index + 1);
3277 break;
3278 case COMP_DICTCOMP:
3279 /* With 'd[k] = v', v is evaluated before k, so we do
3280 the same. */
3281 VISIT(c, expr, val);
3282 VISIT(c, expr, elt);
3283 ADDOP_I(c, MAP_ADD, gen_index + 1);
3284 break;
3285 default:
3286 return 0;
3287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 compiler_use_next_block(c, skip);
3290 }
3291 compiler_use_next_block(c, if_cleanup);
3292 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3293 compiler_use_next_block(c, anchor);
3294
3295 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296}
3297
3298static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003299compiler_comprehension(struct compiler *c, expr_ty e, int type,
3300 identifier name, asdl_seq *generators, expr_ty elt,
3301 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PyCodeObject *co = NULL;
3304 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003305 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 outermost_iter = ((comprehension_ty)
3308 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003309
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003310 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3311 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (type != COMP_GENEXP) {
3315 int op;
3316 switch (type) {
3317 case COMP_LISTCOMP:
3318 op = BUILD_LIST;
3319 break;
3320 case COMP_SETCOMP:
3321 op = BUILD_SET;
3322 break;
3323 case COMP_DICTCOMP:
3324 op = BUILD_MAP;
3325 break;
3326 default:
3327 PyErr_Format(PyExc_SystemError,
3328 "unknown comprehension type %d", type);
3329 goto error_in_scope;
3330 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 ADDOP_I(c, op, 0);
3333 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 if (!compiler_comprehension_generator(c, generators, 0, elt,
3336 val, type))
3337 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 if (type != COMP_GENEXP) {
3340 ADDOP(c, RETURN_VALUE);
3341 }
3342
3343 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003344 qualname = c->u->u_qualname;
3345 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003347 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 goto error;
3349
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003350 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003352 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 Py_DECREF(co);
3354
3355 VISIT(c, expr, outermost_iter);
3356 ADDOP(c, GET_ITER);
3357 ADDOP_I(c, CALL_FUNCTION, 1);
3358 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003359error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003361error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003362 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 Py_XDECREF(co);
3364 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003365}
3366
3367static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368compiler_genexp(struct compiler *c, expr_ty e)
3369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 static identifier name;
3371 if (!name) {
3372 name = PyUnicode_FromString("<genexpr>");
3373 if (!name)
3374 return 0;
3375 }
3376 assert(e->kind == GeneratorExp_kind);
3377 return compiler_comprehension(c, e, COMP_GENEXP, name,
3378 e->v.GeneratorExp.generators,
3379 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380}
3381
3382static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003383compiler_listcomp(struct compiler *c, expr_ty e)
3384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 static identifier name;
3386 if (!name) {
3387 name = PyUnicode_FromString("<listcomp>");
3388 if (!name)
3389 return 0;
3390 }
3391 assert(e->kind == ListComp_kind);
3392 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3393 e->v.ListComp.generators,
3394 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003395}
3396
3397static int
3398compiler_setcomp(struct compiler *c, expr_ty e)
3399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 static identifier name;
3401 if (!name) {
3402 name = PyUnicode_FromString("<setcomp>");
3403 if (!name)
3404 return 0;
3405 }
3406 assert(e->kind == SetComp_kind);
3407 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3408 e->v.SetComp.generators,
3409 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003410}
3411
3412
3413static int
3414compiler_dictcomp(struct compiler *c, expr_ty e)
3415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 static identifier name;
3417 if (!name) {
3418 name = PyUnicode_FromString("<dictcomp>");
3419 if (!name)
3420 return 0;
3421 }
3422 assert(e->kind == DictComp_kind);
3423 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3424 e->v.DictComp.generators,
3425 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003426}
3427
3428
3429static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430compiler_visit_keyword(struct compiler *c, keyword_ty k)
3431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3433 VISIT(c, expr, k->value);
3434 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003435}
3436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438 whether they are true or false.
3439
3440 Return values: 1 for true, 0 for false, -1 for non-constant.
3441 */
3442
3443static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003444expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 char *id;
3447 switch (e->kind) {
3448 case Ellipsis_kind:
3449 return 1;
3450 case Num_kind:
3451 return PyObject_IsTrue(e->v.Num.n);
3452 case Str_kind:
3453 return PyObject_IsTrue(e->v.Str.s);
3454 case Name_kind:
3455 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003457 if (id && strcmp(id, "__debug__") == 0)
3458 return !c->c_optimize;
3459 return -1;
3460 case NameConstant_kind: {
3461 PyObject *o = e->v.NameConstant.value;
3462 if (o == Py_None)
3463 return 0;
3464 else if (o == Py_True)
3465 return 1;
3466 else if (o == Py_False)
3467 return 0;
3468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 default:
3470 return -1;
3471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003472}
3473
Guido van Rossumc2e20742006-02-27 22:32:47 +00003474/*
3475 Implements the with statement from PEP 343.
3476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003478
3479 with EXPR as VAR:
3480 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481
Guido van Rossumc2e20742006-02-27 22:32:47 +00003482 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483
Thomas Wouters477c8d52006-05-27 19:21:47 +00003484 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003485 exit = context.__exit__ # not calling it
3486 value = context.__enter__()
3487 try:
3488 VAR = value # if VAR present in the syntax
3489 BLOCK
3490 finally:
3491 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003493 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003495 exit(*exc)
3496 */
3497static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003498compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003499{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003500 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003501 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003502
3503 assert(s->kind == With_kind);
3504
Guido van Rossumc2e20742006-02-27 22:32:47 +00003505 block = compiler_new_block(c);
3506 finally = compiler_new_block(c);
3507 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003508 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003509
Thomas Wouters477c8d52006-05-27 19:21:47 +00003510 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003511 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003512 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003513
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003514 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003515 compiler_use_next_block(c, block);
3516 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003517 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003518 }
3519
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003520 if (item->optional_vars) {
3521 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003522 }
3523 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003525 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003526 }
3527
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003528 pos++;
3529 if (pos == asdl_seq_LEN(s->v.With.items))
3530 /* BLOCK code */
3531 VISIT_SEQ(c, stmt, s->v.With.body)
3532 else if (!compiler_with(c, s, pos))
3533 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003534
3535 /* End of try block; start the finally block */
3536 ADDOP(c, POP_BLOCK);
3537 compiler_pop_fblock(c, FINALLY_TRY, block);
3538
3539 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3540 compiler_use_next_block(c, finally);
3541 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003542 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003543
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003544 /* Finally block starts; context.__exit__ is on the stack under
3545 the exception or return information. Just issue our magic
3546 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003547 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003548
3549 /* Finally block ends. */
3550 ADDOP(c, END_FINALLY);
3551 compiler_pop_fblock(c, FINALLY_END, finally);
3552 return 1;
3553}
3554
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555static int
3556compiler_visit_expr(struct compiler *c, expr_ty e)
3557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 /* If expr e has a different line number than the last expr/stmt,
3559 set a new line number for the next instruction.
3560 */
3561 if (e->lineno > c->u->u_lineno) {
3562 c->u->u_lineno = e->lineno;
3563 c->u->u_lineno_set = 0;
3564 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003565 /* Updating the column offset is always harmless. */
3566 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 switch (e->kind) {
3568 case BoolOp_kind:
3569 return compiler_boolop(c, e);
3570 case BinOp_kind:
3571 VISIT(c, expr, e->v.BinOp.left);
3572 VISIT(c, expr, e->v.BinOp.right);
3573 ADDOP(c, binop(c, e->v.BinOp.op));
3574 break;
3575 case UnaryOp_kind:
3576 VISIT(c, expr, e->v.UnaryOp.operand);
3577 ADDOP(c, unaryop(e->v.UnaryOp.op));
3578 break;
3579 case Lambda_kind:
3580 return compiler_lambda(c, e);
3581 case IfExp_kind:
3582 return compiler_ifexp(c, e);
3583 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003584 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003586 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 case GeneratorExp_kind:
3588 return compiler_genexp(c, e);
3589 case ListComp_kind:
3590 return compiler_listcomp(c, e);
3591 case SetComp_kind:
3592 return compiler_setcomp(c, e);
3593 case DictComp_kind:
3594 return compiler_dictcomp(c, e);
3595 case Yield_kind:
3596 if (c->u->u_ste->ste_type != FunctionBlock)
3597 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003598 if (e->v.Yield.value) {
3599 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 }
3601 else {
3602 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3603 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003604 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003606 case YieldFrom_kind:
3607 if (c->u->u_ste->ste_type != FunctionBlock)
3608 return compiler_error(c, "'yield' outside function");
3609 VISIT(c, expr, e->v.YieldFrom.value);
3610 ADDOP(c, GET_ITER);
3611 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3612 ADDOP(c, YIELD_FROM);
3613 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 case Compare_kind:
3615 return compiler_compare(c, e);
3616 case Call_kind:
3617 return compiler_call(c, e);
3618 case Num_kind:
3619 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3620 break;
3621 case Str_kind:
3622 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3623 break;
3624 case Bytes_kind:
3625 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3626 break;
3627 case Ellipsis_kind:
3628 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3629 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003630 case NameConstant_kind:
3631 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3632 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 /* The following exprs can be assignment targets. */
3634 case Attribute_kind:
3635 if (e->v.Attribute.ctx != AugStore)
3636 VISIT(c, expr, e->v.Attribute.value);
3637 switch (e->v.Attribute.ctx) {
3638 case AugLoad:
3639 ADDOP(c, DUP_TOP);
3640 /* Fall through to load */
3641 case Load:
3642 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3643 break;
3644 case AugStore:
3645 ADDOP(c, ROT_TWO);
3646 /* Fall through to save */
3647 case Store:
3648 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3649 break;
3650 case Del:
3651 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3652 break;
3653 case Param:
3654 default:
3655 PyErr_SetString(PyExc_SystemError,
3656 "param invalid in attribute expression");
3657 return 0;
3658 }
3659 break;
3660 case Subscript_kind:
3661 switch (e->v.Subscript.ctx) {
3662 case AugLoad:
3663 VISIT(c, expr, e->v.Subscript.value);
3664 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3665 break;
3666 case Load:
3667 VISIT(c, expr, e->v.Subscript.value);
3668 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3669 break;
3670 case AugStore:
3671 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3672 break;
3673 case Store:
3674 VISIT(c, expr, e->v.Subscript.value);
3675 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3676 break;
3677 case Del:
3678 VISIT(c, expr, e->v.Subscript.value);
3679 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3680 break;
3681 case Param:
3682 default:
3683 PyErr_SetString(PyExc_SystemError,
3684 "param invalid in subscript expression");
3685 return 0;
3686 }
3687 break;
3688 case Starred_kind:
3689 switch (e->v.Starred.ctx) {
3690 case Store:
3691 /* In all legitimate cases, the Starred node was already replaced
3692 * by compiler_list/compiler_tuple. XXX: is that okay? */
3693 return compiler_error(c,
3694 "starred assignment target must be in a list or tuple");
3695 default:
3696 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003697 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 }
3699 break;
3700 case Name_kind:
3701 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3702 /* child nodes of List and Tuple will have expr_context set */
3703 case List_kind:
3704 return compiler_list(c, e);
3705 case Tuple_kind:
3706 return compiler_tuple(c, e);
3707 }
3708 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709}
3710
3711static int
3712compiler_augassign(struct compiler *c, stmt_ty s)
3713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 expr_ty e = s->v.AugAssign.target;
3715 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 switch (e->kind) {
3720 case Attribute_kind:
3721 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3722 AugLoad, e->lineno, e->col_offset, c->c_arena);
3723 if (auge == NULL)
3724 return 0;
3725 VISIT(c, expr, auge);
3726 VISIT(c, expr, s->v.AugAssign.value);
3727 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3728 auge->v.Attribute.ctx = AugStore;
3729 VISIT(c, expr, auge);
3730 break;
3731 case Subscript_kind:
3732 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3733 AugLoad, e->lineno, e->col_offset, c->c_arena);
3734 if (auge == NULL)
3735 return 0;
3736 VISIT(c, expr, auge);
3737 VISIT(c, expr, s->v.AugAssign.value);
3738 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3739 auge->v.Subscript.ctx = AugStore;
3740 VISIT(c, expr, auge);
3741 break;
3742 case Name_kind:
3743 if (!compiler_nameop(c, e->v.Name.id, Load))
3744 return 0;
3745 VISIT(c, expr, s->v.AugAssign.value);
3746 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3747 return compiler_nameop(c, e->v.Name.id, Store);
3748 default:
3749 PyErr_Format(PyExc_SystemError,
3750 "invalid node type (%d) for augmented assignment",
3751 e->kind);
3752 return 0;
3753 }
3754 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755}
3756
3757static int
3758compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 struct fblockinfo *f;
3761 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3762 PyErr_SetString(PyExc_SystemError,
3763 "too many statically nested blocks");
3764 return 0;
3765 }
3766 f = &c->u->u_fblock[c->u->u_nfblocks++];
3767 f->fb_type = t;
3768 f->fb_block = b;
3769 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770}
3771
3772static void
3773compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 struct compiler_unit *u = c->u;
3776 assert(u->u_nfblocks > 0);
3777 u->u_nfblocks--;
3778 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3779 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780}
3781
Thomas Wouters89f507f2006-12-13 04:49:30 +00003782static int
3783compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 int i;
3785 struct compiler_unit *u = c->u;
3786 for (i = 0; i < u->u_nfblocks; ++i) {
3787 if (u->u_fblock[i].fb_type == LOOP)
3788 return 1;
3789 }
3790 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003791}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792/* Raises a SyntaxError and returns 0.
3793 If something goes wrong, a different exception may be raised.
3794*/
3795
3796static int
3797compiler_error(struct compiler *c, const char *errstr)
3798{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003799 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801
Victor Stinner14e461d2013-08-26 22:28:21 +02003802 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 if (!loc) {
3804 Py_INCREF(Py_None);
3805 loc = Py_None;
3806 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003807 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003808 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (!u)
3810 goto exit;
3811 v = Py_BuildValue("(zO)", errstr, u);
3812 if (!v)
3813 goto exit;
3814 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 Py_DECREF(loc);
3817 Py_XDECREF(u);
3818 Py_XDECREF(v);
3819 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820}
3821
3822static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823compiler_handle_subscr(struct compiler *c, const char *kind,
3824 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* XXX this code is duplicated */
3829 switch (ctx) {
3830 case AugLoad: /* fall through to Load */
3831 case Load: op = BINARY_SUBSCR; break;
3832 case AugStore:/* fall through to Store */
3833 case Store: op = STORE_SUBSCR; break;
3834 case Del: op = DELETE_SUBSCR; break;
3835 case Param:
3836 PyErr_Format(PyExc_SystemError,
3837 "invalid %s kind %d in subscript\n",
3838 kind, ctx);
3839 return 0;
3840 }
3841 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003842 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 }
3844 else if (ctx == AugStore) {
3845 ADDOP(c, ROT_THREE);
3846 }
3847 ADDOP(c, op);
3848 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849}
3850
3851static int
3852compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 int n = 2;
3855 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 /* only handles the cases where BUILD_SLICE is emitted */
3858 if (s->v.Slice.lower) {
3859 VISIT(c, expr, s->v.Slice.lower);
3860 }
3861 else {
3862 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 if (s->v.Slice.upper) {
3866 VISIT(c, expr, s->v.Slice.upper);
3867 }
3868 else {
3869 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3870 }
3871
3872 if (s->v.Slice.step) {
3873 n++;
3874 VISIT(c, expr, s->v.Slice.step);
3875 }
3876 ADDOP_I(c, BUILD_SLICE, n);
3877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878}
3879
3880static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3882 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 switch (s->kind) {
3885 case Slice_kind:
3886 return compiler_slice(c, s, ctx);
3887 case Index_kind:
3888 VISIT(c, expr, s->v.Index.value);
3889 break;
3890 case ExtSlice_kind:
3891 default:
3892 PyErr_SetString(PyExc_SystemError,
3893 "extended slice invalid in nested slice");
3894 return 0;
3895 }
3896 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897}
3898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899static int
3900compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 char * kindname = NULL;
3903 switch (s->kind) {
3904 case Index_kind:
3905 kindname = "index";
3906 if (ctx != AugStore) {
3907 VISIT(c, expr, s->v.Index.value);
3908 }
3909 break;
3910 case Slice_kind:
3911 kindname = "slice";
3912 if (ctx != AugStore) {
3913 if (!compiler_slice(c, s, ctx))
3914 return 0;
3915 }
3916 break;
3917 case ExtSlice_kind:
3918 kindname = "extended slice";
3919 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01003920 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 for (i = 0; i < n; i++) {
3922 slice_ty sub = (slice_ty)asdl_seq_GET(
3923 s->v.ExtSlice.dims, i);
3924 if (!compiler_visit_nested_slice(c, sub, ctx))
3925 return 0;
3926 }
3927 ADDOP_I(c, BUILD_TUPLE, n);
3928 }
3929 break;
3930 default:
3931 PyErr_Format(PyExc_SystemError,
3932 "invalid subscript kind %d", s->kind);
3933 return 0;
3934 }
3935 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936}
3937
Thomas Wouters89f507f2006-12-13 04:49:30 +00003938/* End of the compiler section, beginning of the assembler section */
3939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940/* do depth-first search of basic block graph, starting with block.
3941 post records the block indices in post-order.
3942
3943 XXX must handle implicit jumps from one block to next
3944*/
3945
Thomas Wouters89f507f2006-12-13 04:49:30 +00003946struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 PyObject *a_bytecode; /* string containing bytecode */
3948 int a_offset; /* offset into bytecode */
3949 int a_nblocks; /* number of reachable blocks */
3950 basicblock **a_postorder; /* list of blocks in dfs postorder */
3951 PyObject *a_lnotab; /* string containing lnotab */
3952 int a_lnotab_off; /* offset into lnotab */
3953 int a_lineno; /* last lineno of emitted instruction */
3954 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003955};
3956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957static void
3958dfs(struct compiler *c, basicblock *b, struct assembler *a)
3959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 int i;
3961 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 if (b->b_seen)
3964 return;
3965 b->b_seen = 1;
3966 if (b->b_next != NULL)
3967 dfs(c, b->b_next, a);
3968 for (i = 0; i < b->b_iused; i++) {
3969 instr = &b->b_instr[i];
3970 if (instr->i_jrel || instr->i_jabs)
3971 dfs(c, instr->i_target, a);
3972 }
3973 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003974}
3975
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003976static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003977stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3978{
Larry Hastings3a907972013-11-23 14:49:22 -08003979 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 struct instr *instr;
3981 if (b->b_seen || b->b_startdepth >= depth)
3982 return maxdepth;
3983 b->b_seen = 1;
3984 b->b_startdepth = depth;
3985 for (i = 0; i < b->b_iused; i++) {
3986 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08003987 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
3988 if (effect == PY_INVALID_STACK_EFFECT) {
3989 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
3990 Py_FatalError("PyCompile_OpcodeStackEffect()");
3991 }
3992 depth += effect;
3993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 if (depth > maxdepth)
3995 maxdepth = depth;
3996 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3997 if (instr->i_jrel || instr->i_jabs) {
3998 target_depth = depth;
3999 if (instr->i_opcode == FOR_ITER) {
4000 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004001 }
4002 else if (instr->i_opcode == SETUP_FINALLY ||
4003 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 target_depth = depth+3;
4005 if (target_depth > maxdepth)
4006 maxdepth = target_depth;
4007 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004008 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4009 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4010 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 maxdepth = stackdepth_walk(c, instr->i_target,
4012 target_depth, maxdepth);
4013 if (instr->i_opcode == JUMP_ABSOLUTE ||
4014 instr->i_opcode == JUMP_FORWARD) {
4015 goto out; /* remaining code is dead */
4016 }
4017 }
4018 }
4019 if (b->b_next)
4020 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 b->b_seen = 0;
4023 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024}
4025
4026/* Find the flow path that needs the largest stack. We assume that
4027 * cycles in the flow graph have no net effect on the stack depth.
4028 */
4029static int
4030stackdepth(struct compiler *c)
4031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 basicblock *b, *entryblock;
4033 entryblock = NULL;
4034 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4035 b->b_seen = 0;
4036 b->b_startdepth = INT_MIN;
4037 entryblock = b;
4038 }
4039 if (!entryblock)
4040 return 0;
4041 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042}
4043
4044static int
4045assemble_init(struct assembler *a, int nblocks, int firstlineno)
4046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 memset(a, 0, sizeof(struct assembler));
4048 a->a_lineno = firstlineno;
4049 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4050 if (!a->a_bytecode)
4051 return 0;
4052 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4053 if (!a->a_lnotab)
4054 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004055 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 PyErr_NoMemory();
4057 return 0;
4058 }
4059 a->a_postorder = (basicblock **)PyObject_Malloc(
4060 sizeof(basicblock *) * nblocks);
4061 if (!a->a_postorder) {
4062 PyErr_NoMemory();
4063 return 0;
4064 }
4065 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066}
4067
4068static void
4069assemble_free(struct assembler *a)
4070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 Py_XDECREF(a->a_bytecode);
4072 Py_XDECREF(a->a_lnotab);
4073 if (a->a_postorder)
4074 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075}
4076
4077/* Return the size of a basic block in bytes. */
4078
4079static int
4080instrsize(struct instr *instr)
4081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 if (!instr->i_hasarg)
4083 return 1; /* 1 byte for the opcode*/
4084 if (instr->i_oparg > 0xffff)
4085 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4086 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087}
4088
4089static int
4090blocksize(basicblock *b)
4091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 int i;
4093 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 for (i = 0; i < b->b_iused; i++)
4096 size += instrsize(&b->b_instr[i]);
4097 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098}
4099
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004100/* Appends a pair to the end of the line number table, a_lnotab, representing
4101 the instruction's bytecode offset and line number. See
4102 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004103
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004104static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004108 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 d_bytecode = a->a_offset - a->a_lineno_off;
4112 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 assert(d_bytecode >= 0);
4115 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 if(d_bytecode == 0 && d_lineno == 0)
4118 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 if (d_bytecode > 255) {
4121 int j, nbytes, ncodes = d_bytecode / 255;
4122 nbytes = a->a_lnotab_off + 2 * ncodes;
4123 len = PyBytes_GET_SIZE(a->a_lnotab);
4124 if (nbytes >= len) {
4125 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4126 len = nbytes;
4127 else if (len <= INT_MAX / 2)
4128 len *= 2;
4129 else {
4130 PyErr_NoMemory();
4131 return 0;
4132 }
4133 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4134 return 0;
4135 }
4136 lnotab = (unsigned char *)
4137 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4138 for (j = 0; j < ncodes; j++) {
4139 *lnotab++ = 255;
4140 *lnotab++ = 0;
4141 }
4142 d_bytecode -= ncodes * 255;
4143 a->a_lnotab_off += ncodes * 2;
4144 }
4145 assert(d_bytecode <= 255);
4146 if (d_lineno > 255) {
4147 int j, nbytes, ncodes = d_lineno / 255;
4148 nbytes = a->a_lnotab_off + 2 * ncodes;
4149 len = PyBytes_GET_SIZE(a->a_lnotab);
4150 if (nbytes >= len) {
4151 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4152 len = nbytes;
4153 else if (len <= INT_MAX / 2)
4154 len *= 2;
4155 else {
4156 PyErr_NoMemory();
4157 return 0;
4158 }
4159 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4160 return 0;
4161 }
4162 lnotab = (unsigned char *)
4163 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4164 *lnotab++ = d_bytecode;
4165 *lnotab++ = 255;
4166 d_bytecode = 0;
4167 for (j = 1; j < ncodes; j++) {
4168 *lnotab++ = 0;
4169 *lnotab++ = 255;
4170 }
4171 d_lineno -= ncodes * 255;
4172 a->a_lnotab_off += ncodes * 2;
4173 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 len = PyBytes_GET_SIZE(a->a_lnotab);
4176 if (a->a_lnotab_off + 2 >= len) {
4177 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4178 return 0;
4179 }
4180 lnotab = (unsigned char *)
4181 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 a->a_lnotab_off += 2;
4184 if (d_bytecode) {
4185 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004186 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 }
4188 else { /* First line of a block; def stmt, etc. */
4189 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004190 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 }
4192 a->a_lineno = i->i_lineno;
4193 a->a_lineno_off = a->a_offset;
4194 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004195}
4196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197/* assemble_emit()
4198 Extend the bytecode with a new instruction.
4199 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004200*/
4201
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004202static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 int size, arg = 0, ext = 0;
4206 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4207 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 size = instrsize(i);
4210 if (i->i_hasarg) {
4211 arg = i->i_oparg;
4212 ext = arg >> 16;
4213 }
4214 if (i->i_lineno && !assemble_lnotab(a, i))
4215 return 0;
4216 if (a->a_offset + size >= len) {
4217 if (len > PY_SSIZE_T_MAX / 2)
4218 return 0;
4219 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4220 return 0;
4221 }
4222 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4223 a->a_offset += size;
4224 if (size == 6) {
4225 assert(i->i_hasarg);
4226 *code++ = (char)EXTENDED_ARG;
4227 *code++ = ext & 0xff;
4228 *code++ = ext >> 8;
4229 arg &= 0xffff;
4230 }
4231 *code++ = i->i_opcode;
4232 if (i->i_hasarg) {
4233 assert(size == 3 || size == 6);
4234 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004235 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 }
4237 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004238}
4239
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004240static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 basicblock *b;
4244 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4245 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 /* Compute the size of each block and fixup jump args.
4248 Replace block pointer with position in bytecode. */
4249 do {
4250 totsize = 0;
4251 for (i = a->a_nblocks - 1; i >= 0; i--) {
4252 b = a->a_postorder[i];
4253 bsize = blocksize(b);
4254 b->b_offset = totsize;
4255 totsize += bsize;
4256 }
4257 last_extended_arg_count = extended_arg_count;
4258 extended_arg_count = 0;
4259 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4260 bsize = b->b_offset;
4261 for (i = 0; i < b->b_iused; i++) {
4262 struct instr *instr = &b->b_instr[i];
4263 /* Relative jumps are computed relative to
4264 the instruction pointer after fetching
4265 the jump instruction.
4266 */
4267 bsize += instrsize(instr);
4268 if (instr->i_jabs)
4269 instr->i_oparg = instr->i_target->b_offset;
4270 else if (instr->i_jrel) {
4271 int delta = instr->i_target->b_offset - bsize;
4272 instr->i_oparg = delta;
4273 }
4274 else
4275 continue;
4276 if (instr->i_oparg > 0xffff)
4277 extended_arg_count++;
4278 }
4279 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* XXX: This is an awful hack that could hurt performance, but
4282 on the bright side it should work until we come up
4283 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 The issue is that in the first loop blocksize() is called
4286 which calls instrsize() which requires i_oparg be set
4287 appropriately. There is a bootstrap problem because
4288 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 So we loop until we stop seeing new EXTENDED_ARGs.
4291 The only EXTENDED_ARGs that could be popping up are
4292 ones in jump instructions. So this should converge
4293 fairly quickly.
4294 */
4295 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004296}
4297
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004298static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004299dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 PyObject *tuple, *k, *v;
4302 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 tuple = PyTuple_New(size);
4305 if (tuple == NULL)
4306 return NULL;
4307 while (PyDict_Next(dict, &pos, &k, &v)) {
4308 i = PyLong_AS_LONG(v);
4309 /* The keys of the dictionary are tuples. (see compiler_add_o)
4310 The object we want is always first, though. */
4311 k = PyTuple_GET_ITEM(k, 0);
4312 Py_INCREF(k);
4313 assert((i - offset) < size);
4314 assert((i - offset) >= 0);
4315 PyTuple_SET_ITEM(tuple, i - offset, k);
4316 }
4317 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004318}
4319
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004320static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004324 int flags = 0;
4325 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004327 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 if (ste->ste_nested)
4329 flags |= CO_NESTED;
4330 if (ste->ste_generator)
4331 flags |= CO_GENERATOR;
4332 if (ste->ste_varargs)
4333 flags |= CO_VARARGS;
4334 if (ste->ste_varkeywords)
4335 flags |= CO_VARKEYWORDS;
4336 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 /* (Only) inherit compilerflags in PyCF_MASK */
4339 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 n = PyDict_Size(c->u->u_freevars);
4342 if (n < 0)
4343 return -1;
4344 if (n == 0) {
4345 n = PyDict_Size(c->u->u_cellvars);
4346 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004347 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004349 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 }
4351 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004354}
4355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004356static PyCodeObject *
4357makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 PyObject *tmp;
4360 PyCodeObject *co = NULL;
4361 PyObject *consts = NULL;
4362 PyObject *names = NULL;
4363 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 PyObject *name = NULL;
4365 PyObject *freevars = NULL;
4366 PyObject *cellvars = NULL;
4367 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004368 Py_ssize_t nlocals;
4369 int nlocals_int;
4370 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004371 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 tmp = dict_keys_inorder(c->u->u_consts, 0);
4374 if (!tmp)
4375 goto error;
4376 consts = PySequence_List(tmp); /* optimize_code requires a list */
4377 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 names = dict_keys_inorder(c->u->u_names, 0);
4380 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4381 if (!consts || !names || !varnames)
4382 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4385 if (!cellvars)
4386 goto error;
4387 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4388 if (!freevars)
4389 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004392 assert(nlocals < INT_MAX);
4393 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 flags = compute_code_flags(c);
4396 if (flags < 0)
4397 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4400 if (!bytecode)
4401 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4404 if (!tmp)
4405 goto error;
4406 Py_DECREF(consts);
4407 consts = tmp;
4408
Victor Stinnerf8e32212013-11-19 23:56:34 +01004409 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4410 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4411 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004412 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 bytecode, consts, names, varnames,
4414 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004415 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 c->u->u_firstlineno,
4417 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 Py_XDECREF(consts);
4420 Py_XDECREF(names);
4421 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 Py_XDECREF(name);
4423 Py_XDECREF(freevars);
4424 Py_XDECREF(cellvars);
4425 Py_XDECREF(bytecode);
4426 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004427}
4428
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004429
4430/* For debugging purposes only */
4431#if 0
4432static void
4433dump_instr(const struct instr *i)
4434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 const char *jrel = i->i_jrel ? "jrel " : "";
4436 const char *jabs = i->i_jabs ? "jabs " : "";
4437 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 *arg = '\0';
4440 if (i->i_hasarg)
4441 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4444 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004445}
4446
4447static void
4448dump_basicblock(const basicblock *b)
4449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 const char *seen = b->b_seen ? "seen " : "";
4451 const char *b_return = b->b_return ? "return " : "";
4452 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4453 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4454 if (b->b_instr) {
4455 int i;
4456 for (i = 0; i < b->b_iused; i++) {
4457 fprintf(stderr, " [%02d] ", i);
4458 dump_instr(b->b_instr + i);
4459 }
4460 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004461}
4462#endif
4463
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004464static PyCodeObject *
4465assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 basicblock *b, *entryblock;
4468 struct assembler a;
4469 int i, j, nblocks;
4470 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 /* Make sure every block that falls off the end returns None.
4473 XXX NEXT_BLOCK() isn't quite right, because if the last
4474 block ends with a jump or return b_next shouldn't set.
4475 */
4476 if (!c->u->u_curblock->b_return) {
4477 NEXT_BLOCK(c);
4478 if (addNone)
4479 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4480 ADDOP(c, RETURN_VALUE);
4481 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 nblocks = 0;
4484 entryblock = NULL;
4485 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4486 nblocks++;
4487 entryblock = b;
4488 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 /* Set firstlineno if it wasn't explicitly set. */
4491 if (!c->u->u_firstlineno) {
4492 if (entryblock && entryblock->b_instr)
4493 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4494 else
4495 c->u->u_firstlineno = 1;
4496 }
4497 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4498 goto error;
4499 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 /* Can't modify the bytecode after computing jump offsets. */
4502 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 /* Emit code in reverse postorder from dfs. */
4505 for (i = a.a_nblocks - 1; i >= 0; i--) {
4506 b = a.a_postorder[i];
4507 for (j = 0; j < b->b_iused; j++)
4508 if (!assemble_emit(&a, &b->b_instr[j]))
4509 goto error;
4510 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4513 goto error;
4514 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4515 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004518 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 assemble_free(&a);
4520 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004521}
Georg Brandl8334fd92010-12-04 10:26:46 +00004522
4523#undef PyAST_Compile
4524PyAPI_FUNC(PyCodeObject *)
4525PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4526 PyArena *arena)
4527{
4528 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4529}
4530