blob: 29b88ff0e3dccb0b9bfeb1e8e6253e7b6ad4221b [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,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinnerad9a0662013-11-19 22:23:20 +0100199static int compiler_call_helper(struct compiler *c, Py_ssize_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static PyCodeObject *assemble(struct compiler *, int addNone);
206static PyObject *__doc__;
207
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400208#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* Name mangling: __private becomes _classname__private.
214 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200215 PyObject *result;
216 size_t nlen, plen, ipriv;
217 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 PyUnicode_READ_CHAR(ident, 0) != '_' ||
220 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_INCREF(ident);
222 return ident;
223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 nlen = PyUnicode_GET_LENGTH(ident);
225 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 The only time a name with a dot can occur is when
229 we are compiling an import statement that has a
230 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 TODO(jhylton): Decide whether we want to support
233 mangling of the module name, e.g. __M.X.
234 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
236 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
237 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident; /* Don't mangle __whatever__ */
240 }
241 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 ipriv = 0;
243 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
244 ipriv++;
245 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle if class is just underscores */
248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000250
Antoine Pitrou55bff892013-04-06 21:21:04 +0200251 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
252 PyErr_SetString(PyExc_OverflowError,
253 "private identifier too large to be mangled");
254 return NULL;
255 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
258 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
259 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
260
261 result = PyUnicode_New(1 + nlen + plen, maxchar);
262 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
265 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200266 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
267 Py_DECREF(result);
268 return NULL;
269 }
270 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
271 Py_DECREF(result);
272 return NULL;
273 }
Victor Stinner8f825062012-04-27 13:55:39 +0200274 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000276}
277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278static int
279compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 c->c_stack = PyList_New(0);
284 if (!c->c_stack)
285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288}
289
290PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200291PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
292 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct compiler c;
295 PyCodeObject *co = NULL;
296 PyCompilerFlags local_flags;
297 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!__doc__) {
300 __doc__ = PyUnicode_InternFromString("__doc__");
301 if (!__doc__)
302 return NULL;
303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!compiler_init(&c))
306 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200307 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 c.c_filename = filename;
309 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200310 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (c.c_future == NULL)
312 goto finally;
313 if (!flags) {
314 local_flags.cf_flags = 0;
315 flags = &local_flags;
316 }
317 merged = c.c_future->ff_features | flags->cf_flags;
318 c.c_future->ff_features = merged;
319 flags->cf_flags = merged;
320 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000321 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Victor Stinner14e461d2013-08-26 22:28:21 +0200324 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (c.c_st == NULL) {
326 if (!PyErr_Occurred())
327 PyErr_SetString(PyExc_SystemError, "no symtable");
328 goto finally;
329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Thomas Wouters1175c432006-02-27 22:49:54 +0000333 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 compiler_free(&c);
335 assert(co || PyErr_Occurred());
336 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337}
338
339PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200340PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
341 int optimize, PyArena *arena)
342{
343 PyObject *filename;
344 PyCodeObject *co;
345 filename = PyUnicode_DecodeFSDefault(filename_str);
346 if (filename == NULL)
347 return NULL;
348 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
349 Py_DECREF(filename);
350 return co;
351
352}
353
354PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355PyNode_Compile(struct _node *n, const char *filename)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyCodeObject *co = NULL;
358 mod_ty mod;
359 PyArena *arena = PyArena_New();
360 if (!arena)
361 return NULL;
362 mod = PyAST_FromNode(n, NULL, filename, arena);
363 if (mod)
364 co = PyAST_Compile(mod, filename, NULL, arena);
365 PyArena_Free(arena);
366 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000367}
368
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000369static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (c->c_st)
373 PySymtable_Free(c->c_st);
374 if (c->c_future)
375 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200376 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000378}
379
Guido van Rossum79f25d91997-04-29 20:08:16 +0000380static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t i, n;
384 PyObject *v, *k;
385 PyObject *dict = PyDict_New();
386 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 n = PyList_Size(list);
389 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100390 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!v) {
392 Py_DECREF(dict);
393 return NULL;
394 }
395 k = PyList_GET_ITEM(list, i);
396 k = PyTuple_Pack(2, k, k->ob_type);
397 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
398 Py_XDECREF(k);
399 Py_DECREF(v);
400 Py_DECREF(dict);
401 return NULL;
402 }
403 Py_DECREF(k);
404 Py_DECREF(v);
405 }
406 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407}
408
409/* Return new dict containing names from src that match scope(s).
410
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000413values are integers, starting at offset and increasing by one for
414each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415*/
416
417static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100418dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700420 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500422 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 assert(offset >= 0);
425 if (dest == NULL)
426 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Meador Inge2ca63152012-07-18 14:20:11 -0500428 /* Sort the keys so that we have a deterministic order on the indexes
429 saved in the returned dictionary. These indexes are used as indexes
430 into the free and cell var storage. Therefore if they aren't
431 deterministic, then the generated bytecode is not deterministic.
432 */
433 sorted_keys = PyDict_Keys(src);
434 if (sorted_keys == NULL)
435 return NULL;
436 if (PyList_Sort(sorted_keys) != 0) {
437 Py_DECREF(sorted_keys);
438 return NULL;
439 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500440 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500441
442 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* XXX this should probably be a macro in symtable.h */
444 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500445 k = PyList_GET_ITEM(sorted_keys, key_i);
446 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 assert(PyLong_Check(v));
448 vi = PyLong_AS_LONG(v);
449 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100452 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500454 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(dest);
456 return NULL;
457 }
458 i++;
459 tuple = PyTuple_Pack(2, k, k->ob_type);
460 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500461 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 Py_DECREF(item);
463 Py_DECREF(dest);
464 Py_XDECREF(tuple);
465 return NULL;
466 }
467 Py_DECREF(item);
468 Py_DECREF(tuple);
469 }
470 }
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000473}
474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475static void
476compiler_unit_check(struct compiler_unit *u)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 basicblock *block;
479 for (block = u->u_blocks; block != NULL; block = block->b_list) {
480 assert((void *)block != (void *)0xcbcbcbcb);
481 assert((void *)block != (void *)0xfbfbfbfb);
482 assert((void *)block != (void *)0xdbdbdbdb);
483 if (block->b_instr != NULL) {
484 assert(block->b_ialloc > 0);
485 assert(block->b_iused > 0);
486 assert(block->b_ialloc >= block->b_iused);
487 }
488 else {
489 assert (block->b_iused == 0);
490 assert (block->b_ialloc == 0);
491 }
492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493}
494
495static void
496compiler_unit_free(struct compiler_unit *u)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 compiler_unit_check(u);
501 b = u->u_blocks;
502 while (b != NULL) {
503 if (b->b_instr)
504 PyObject_Free((void *)b->b_instr);
505 next = b->b_list;
506 PyObject_Free((void *)b);
507 b = next;
508 }
509 Py_CLEAR(u->u_ste);
510 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400511 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_CLEAR(u->u_consts);
513 Py_CLEAR(u->u_names);
514 Py_CLEAR(u->u_varnames);
515 Py_CLEAR(u->u_freevars);
516 Py_CLEAR(u->u_cellvars);
517 Py_CLEAR(u->u_private);
518 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519}
520
521static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100522compiler_enter_scope(struct compiler *c, identifier name,
523 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
551 /* Cook up a implicit __class__ cell. */
552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
562 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
623 if (compiler_use_new_block(c) == NULL)
624 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400626 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
627 if (!compiler_set_qualname(c))
628 return 0;
629 }
630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632}
633
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000634static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635compiler_exit_scope(struct compiler *c)
636{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100637 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 c->c_nestlevel--;
641 compiler_unit_free(c->u);
642 /* Restore c->u to the parent unit. */
643 n = PyList_GET_SIZE(c->c_stack) - 1;
644 if (n >= 0) {
645 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400646 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 assert(c->u);
648 /* we are deleting from a list so this really shouldn't fail */
649 if (PySequence_DelItem(c->c_stack, n) < 0)
650 Py_FatalError("compiler_exit_scope()");
651 compiler_unit_check(c->u);
652 }
653 else
654 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658static int
659compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400662 _Py_static_string(dot_locals, ".<locals>");
663 Py_ssize_t stack_size;
664 struct compiler_unit *u = c->u;
665 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400669 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 if (stack_size > 1) {
671 int scope, force_global = 0;
672 struct compiler_unit *parent;
673 PyObject *mangled, *capsule;
674
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400675 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400676 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 assert(parent);
678
Yury Selivanov75445082015-05-11 22:57:16 -0400679 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
680 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
681 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 assert(u->u_name);
683 mangled = _Py_Mangle(parent->u_private, u->u_name);
684 if (!mangled)
685 return 0;
686 scope = PyST_GetScope(parent->u_ste, mangled);
687 Py_DECREF(mangled);
688 assert(scope != GLOBAL_IMPLICIT);
689 if (scope == GLOBAL_EXPLICIT)
690 force_global = 1;
691 }
692
693 if (!force_global) {
694 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400695 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
697 dot_locals_str = _PyUnicode_FromId(&dot_locals);
698 if (dot_locals_str == NULL)
699 return 0;
700 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
701 if (base == NULL)
702 return 0;
703 }
704 else {
705 Py_INCREF(parent->u_qualname);
706 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100708 }
709 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400711 if (base != NULL) {
712 dot_str = _PyUnicode_FromId(&dot);
713 if (dot_str == NULL) {
714 Py_DECREF(base);
715 return 0;
716 }
717 name = PyUnicode_Concat(base, dot_str);
718 Py_DECREF(base);
719 if (name == NULL)
720 return 0;
721 PyUnicode_Append(&name, u->u_name);
722 if (name == NULL)
723 return 0;
724 }
725 else {
726 Py_INCREF(u->u_name);
727 name = u->u_name;
728 }
729 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100732}
733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734/* Allocate a new block and return a pointer to it.
735 Returns NULL on error.
736*/
737
738static basicblock *
739compiler_new_block(struct compiler *c)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 basicblock *b;
742 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 u = c->u;
745 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
746 if (b == NULL) {
747 PyErr_NoMemory();
748 return NULL;
749 }
750 memset((void *)b, 0, sizeof(basicblock));
751 /* Extend the singly linked list of blocks with new block. */
752 b->b_list = u->u_blocks;
753 u->u_blocks = b;
754 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755}
756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757static basicblock *
758compiler_use_new_block(struct compiler *c)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 basicblock *block = compiler_new_block(c);
761 if (block == NULL)
762 return NULL;
763 c->u->u_curblock = block;
764 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
767static basicblock *
768compiler_next_block(struct compiler *c)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 basicblock *block = compiler_new_block(c);
771 if (block == NULL)
772 return NULL;
773 c->u->u_curblock->b_next = block;
774 c->u->u_curblock = block;
775 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
778static basicblock *
779compiler_use_next_block(struct compiler *c, basicblock *block)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 assert(block != NULL);
782 c->u->u_curblock->b_next = block;
783 c->u->u_curblock = block;
784 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785}
786
787/* Returns the offset of the next instruction in the current block's
788 b_instr array. Resizes the b_instr as necessary.
789 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000790*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791
792static int
793compiler_next_instr(struct compiler *c, basicblock *b)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(b != NULL);
796 if (b->b_instr == NULL) {
797 b->b_instr = (struct instr *)PyObject_Malloc(
798 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
799 if (b->b_instr == NULL) {
800 PyErr_NoMemory();
801 return -1;
802 }
803 b->b_ialloc = DEFAULT_BLOCK_SIZE;
804 memset((char *)b->b_instr, 0,
805 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
806 }
807 else if (b->b_iused == b->b_ialloc) {
808 struct instr *tmp;
809 size_t oldsize, newsize;
810 oldsize = b->b_ialloc * sizeof(struct instr);
811 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (oldsize > (PY_SIZE_MAX >> 1)) {
814 PyErr_NoMemory();
815 return -1;
816 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (newsize == 0) {
819 PyErr_NoMemory();
820 return -1;
821 }
822 b->b_ialloc <<= 1;
823 tmp = (struct instr *)PyObject_Realloc(
824 (void *)b->b_instr, newsize);
825 if (tmp == NULL) {
826 PyErr_NoMemory();
827 return -1;
828 }
829 b->b_instr = tmp;
830 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
831 }
832 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833}
834
Christian Heimes2202f872008-02-06 14:31:34 +0000835/* Set the i_lineno member of the instruction at offset off if the
836 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 already been set. If it has been set, the call has no effect.
838
Christian Heimes2202f872008-02-06 14:31:34 +0000839 The line number is reset in the following cases:
840 - when entering a new scope
841 - on each statement
842 - on each expression that start a new line
843 - before the "except" clause
844 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847static void
848compiler_set_lineno(struct compiler *c, int off)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 basicblock *b;
851 if (c->u->u_lineno_set)
852 return;
853 c->u->u_lineno_set = 1;
854 b = c->u->u_curblock;
855 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856}
857
Larry Hastings3a907972013-11-23 14:49:22 -0800858int
859PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 switch (opcode) {
862 case POP_TOP:
863 return -1;
864 case ROT_TWO:
865 case ROT_THREE:
866 return 0;
867 case DUP_TOP:
868 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000869 case DUP_TOP_TWO:
870 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case UNARY_POSITIVE:
873 case UNARY_NEGATIVE:
874 case UNARY_NOT:
875 case UNARY_INVERT:
876 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case SET_ADD:
879 case LIST_APPEND:
880 return -1;
881 case MAP_ADD:
882 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 case BINARY_POWER:
885 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400886 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 case BINARY_MODULO:
888 case BINARY_ADD:
889 case BINARY_SUBTRACT:
890 case BINARY_SUBSCR:
891 case BINARY_FLOOR_DIVIDE:
892 case BINARY_TRUE_DIVIDE:
893 return -1;
894 case INPLACE_FLOOR_DIVIDE:
895 case INPLACE_TRUE_DIVIDE:
896 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case INPLACE_ADD:
899 case INPLACE_SUBTRACT:
900 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400901 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case INPLACE_MODULO:
903 return -1;
904 case STORE_SUBSCR:
905 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case DELETE_SUBSCR:
907 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 case BINARY_LSHIFT:
910 case BINARY_RSHIFT:
911 case BINARY_AND:
912 case BINARY_XOR:
913 case BINARY_OR:
914 return -1;
915 case INPLACE_POWER:
916 return -1;
917 case GET_ITER:
918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case PRINT_EXPR:
921 return -1;
922 case LOAD_BUILD_CLASS:
923 return 1;
924 case INPLACE_LSHIFT:
925 case INPLACE_RSHIFT:
926 case INPLACE_AND:
927 case INPLACE_XOR:
928 case INPLACE_OR:
929 return -1;
930 case BREAK_LOOP:
931 return 0;
932 case SETUP_WITH:
933 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400934 case WITH_CLEANUP_START:
935 return 1;
936 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case RETURN_VALUE:
939 return -1;
940 case IMPORT_STAR:
941 return -1;
942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
979 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400980 case BUILD_LIST_UNPACK:
981 case BUILD_TUPLE_UNPACK:
982 case BUILD_SET_UNPACK:
983 case BUILD_MAP_UNPACK:
984 return 1 - oparg;
985 case BUILD_MAP_UNPACK_WITH_CALL:
986 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case BUILD_MAP:
988 return 1;
989 case LOAD_ATTR:
990 return 0;
991 case COMPARE_OP:
992 return -1;
993 case IMPORT_NAME:
994 return -1;
995 case IMPORT_FROM:
996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case JUMP_FORWARD:
999 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1000 case JUMP_IF_FALSE_OR_POP: /* "" */
1001 case JUMP_ABSOLUTE:
1002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case POP_JUMP_IF_FALSE:
1005 case POP_JUMP_IF_TRUE:
1006 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_GLOBAL:
1009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case CONTINUE_LOOP:
1012 return 0;
1013 case SETUP_LOOP:
1014 return 0;
1015 case SETUP_EXCEPT:
1016 case SETUP_FINALLY:
1017 return 6; /* can push 3 values for the new exception
1018 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_FAST:
1021 return 1;
1022 case STORE_FAST:
1023 return -1;
1024 case DELETE_FAST:
1025 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case RAISE_VARARGS:
1028 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001029#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case CALL_FUNCTION:
1031 return -NARGS(oparg);
1032 case CALL_FUNCTION_VAR:
1033 case CALL_FUNCTION_KW:
1034 return -NARGS(oparg)-1;
1035 case CALL_FUNCTION_VAR_KW:
1036 return -NARGS(oparg)-2;
1037 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001038 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001040 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001041#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case BUILD_SLICE:
1043 if (oparg == 3)
1044 return -2;
1045 else
1046 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 case LOAD_CLOSURE:
1049 return 1;
1050 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001051 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 return 1;
1053 case STORE_DEREF:
1054 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001055 case DELETE_DEREF:
1056 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001057 case GET_AWAITABLE:
1058 return 0;
1059 case SETUP_ASYNC_WITH:
1060 return 6;
1061 case BEFORE_ASYNC_WITH:
1062 return 1;
1063 case GET_AITER:
1064 return 0;
1065 case GET_ANEXT:
1066 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001068 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 }
Larry Hastings3a907972013-11-23 14:49:22 -08001070 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073/* Add an opcode with no argument.
1074 Returns 0 on failure, 1 on success.
1075*/
1076
1077static int
1078compiler_addop(struct compiler *c, int opcode)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 basicblock *b;
1081 struct instr *i;
1082 int off;
1083 off = compiler_next_instr(c, c->u->u_curblock);
1084 if (off < 0)
1085 return 0;
1086 b = c->u->u_curblock;
1087 i = &b->b_instr[off];
1088 i->i_opcode = opcode;
1089 i->i_hasarg = 0;
1090 if (opcode == RETURN_VALUE)
1091 b->b_return = 1;
1092 compiler_set_lineno(c, off);
1093 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094}
1095
Victor Stinnerf8e32212013-11-19 23:56:34 +01001096static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *t, *v;
1100 Py_ssize_t arg;
1101 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102
Serhiy Storchaka95949422013-08-27 19:40:23 +03001103 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1105 if (PyFloat_Check(o)) {
1106 d = PyFloat_AS_DOUBLE(o);
1107 /* all we need is to make the tuple different in either the 0.0
1108 * or -0.0 case from all others, just to avoid the "coercion".
1109 */
1110 if (d == 0.0 && copysign(1.0, d) < 0.0)
1111 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1112 else
1113 t = PyTuple_Pack(2, o, o->ob_type);
1114 }
1115 else if (PyComplex_Check(o)) {
1116 Py_complex z;
1117 int real_negzero, imag_negzero;
1118 /* For the complex case we must make complex(x, 0.)
1119 different from complex(x, -0.) and complex(0., y)
1120 different from complex(-0., y), for any x and y.
1121 All four complex zeros must be distinguished.*/
1122 z = PyComplex_AsCComplex(o);
1123 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1124 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1125 if (real_negzero && imag_negzero) {
1126 t = PyTuple_Pack(5, o, o->ob_type,
1127 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 else if (imag_negzero) {
1130 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 else if (real_negzero) {
1133 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1134 }
1135 else {
1136 t = PyTuple_Pack(2, o, o->ob_type);
1137 }
1138 }
1139 else {
1140 t = PyTuple_Pack(2, o, o->ob_type);
1141 }
1142 if (t == NULL)
1143 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 v = PyDict_GetItem(dict, t);
1146 if (!v) {
1147 if (PyErr_Occurred())
1148 return -1;
1149 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001150 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (!v) {
1152 Py_DECREF(t);
1153 return -1;
1154 }
1155 if (PyDict_SetItem(dict, t, v) < 0) {
1156 Py_DECREF(t);
1157 Py_DECREF(v);
1158 return -1;
1159 }
1160 Py_DECREF(v);
1161 }
1162 else
1163 arg = PyLong_AsLong(v);
1164 Py_DECREF(t);
1165 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
1168static int
1169compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001172 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001174 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 return compiler_addop_i(c, opcode, arg);
1176}
1177
1178static int
1179compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001182 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1184 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001185 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 arg = compiler_add_o(c, dict, mangled);
1187 Py_DECREF(mangled);
1188 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001189 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190 return compiler_addop_i(c, opcode, arg);
1191}
1192
1193/* Add an opcode with an integer argument.
1194 Returns 0 on failure, 1 on success.
1195*/
1196
1197static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001198compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 struct instr *i;
1201 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001202
1203 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1204 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001205 assert((-2147483647-1) <= oparg);
1206 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 off = compiler_next_instr(c, c->u->u_curblock);
1209 if (off < 0)
1210 return 0;
1211 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001212 i->i_opcode = opcode;
1213 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 i->i_hasarg = 1;
1215 compiler_set_lineno(c, off);
1216 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217}
1218
1219static int
1220compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 struct instr *i;
1223 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 assert(b != NULL);
1226 off = compiler_next_instr(c, c->u->u_curblock);
1227 if (off < 0)
1228 return 0;
1229 i = &c->u->u_curblock->b_instr[off];
1230 i->i_opcode = opcode;
1231 i->i_target = b;
1232 i->i_hasarg = 1;
1233 if (absolute)
1234 i->i_jabs = 1;
1235 else
1236 i->i_jrel = 1;
1237 compiler_set_lineno(c, off);
1238 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239}
1240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1242 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243 it as the current block. NEXT_BLOCK() also creates an implicit jump
1244 from the current block to the new block.
1245*/
1246
Thomas Wouters89f507f2006-12-13 04:49:30 +00001247/* The returns inside these macros make it impossible to decref objects
1248 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249*/
1250
1251
1252#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (compiler_use_new_block((C)) == NULL) \
1254 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (compiler_next_block((C)) == NULL) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop((C), (OP))) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001267#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop((C), (OP))) { \
1269 compiler_exit_scope(c); \
1270 return 0; \
1271 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001272}
1273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1276 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
1284#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_addop_i((C), (OP), (O))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_addop_j((C), (OP), (O), 1)) \
1291 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292}
1293
1294#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!compiler_addop_j((C), (OP), (O), 0)) \
1296 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
1299/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1300 the ASDL name to synthesize the name of the C type and the visit function.
1301*/
1302
1303#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (!compiler_visit_ ## TYPE((C), (V))) \
1305 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (!compiler_visit_ ## TYPE((C), (V))) { \
1310 compiler_exit_scope(c); \
1311 return 0; \
1312 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001313}
1314
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!compiler_visit_slice((C), (V), (CTX))) \
1317 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318}
1319
1320#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 int _i; \
1322 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1323 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1324 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1325 if (!compiler_visit_ ## TYPE((C), elt)) \
1326 return 0; \
1327 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328}
1329
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001330#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 int _i; \
1332 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1333 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1334 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1335 if (!compiler_visit_ ## TYPE((C), elt)) { \
1336 compiler_exit_scope(c); \
1337 return 0; \
1338 } \
1339 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001340}
1341
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342static int
1343compiler_isdocstring(stmt_ty s)
1344{
1345 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return s->v.Expr.value->kind == Str_kind;
1348}
1349
1350/* Compile a sequence of statements, checking for a docstring. */
1351
1352static int
1353compiler_body(struct compiler *c, asdl_seq *stmts)
1354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 int i = 0;
1356 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!asdl_seq_LEN(stmts))
1359 return 1;
1360 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001361 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* don't generate docstrings if -OO */
1363 i = 1;
1364 VISIT(c, expr, st->v.Expr.value);
1365 if (!compiler_nameop(c, __doc__, Store))
1366 return 0;
1367 }
1368 for (; i < asdl_seq_LEN(stmts); i++)
1369 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1370 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371}
1372
1373static PyCodeObject *
1374compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyCodeObject *co;
1377 int addNone = 1;
1378 static PyObject *module;
1379 if (!module) {
1380 module = PyUnicode_InternFromString("<module>");
1381 if (!module)
1382 return NULL;
1383 }
1384 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001385 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
1387 switch (mod->kind) {
1388 case Module_kind:
1389 if (!compiler_body(c, mod->v.Module.body)) {
1390 compiler_exit_scope(c);
1391 return 0;
1392 }
1393 break;
1394 case Interactive_kind:
1395 c->c_interactive = 1;
1396 VISIT_SEQ_IN_SCOPE(c, stmt,
1397 mod->v.Interactive.body);
1398 break;
1399 case Expression_kind:
1400 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1401 addNone = 0;
1402 break;
1403 case Suite_kind:
1404 PyErr_SetString(PyExc_SystemError,
1405 "suite should not be possible");
1406 return 0;
1407 default:
1408 PyErr_Format(PyExc_SystemError,
1409 "module kind %d should not be possible",
1410 mod->kind);
1411 return 0;
1412 }
1413 co = assemble(c, addNone);
1414 compiler_exit_scope(c);
1415 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001416}
1417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418/* The test for LOCAL must come before the test for FREE in order to
1419 handle classes where name is both local and free. The local var is
1420 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001421*/
1422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423static int
1424get_ref_type(struct compiler *c, PyObject *name)
1425{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001426 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001427 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1428 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1429 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001430 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (scope == 0) {
1432 char buf[350];
1433 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001434 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001436 PyUnicode_AsUTF8(name),
1437 PyUnicode_AsUTF8(c->u->u_name),
1438 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1439 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1440 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1441 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 );
1443 Py_FatalError(buf);
1444 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447}
1448
1449static int
1450compiler_lookup_arg(PyObject *dict, PyObject *name)
1451{
1452 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001453 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001455 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001457 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001459 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001460 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461}
1462
1463static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001464compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001466 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001467 if (qualname == NULL)
1468 qualname = co->co_name;
1469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (free == 0) {
1471 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001472 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 ADDOP_I(c, MAKE_FUNCTION, args);
1474 return 1;
1475 }
1476 for (i = 0; i < free; ++i) {
1477 /* Bypass com_addop_varname because it will generate
1478 LOAD_DEREF but LOAD_CLOSURE is needed.
1479 */
1480 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1481 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 /* Special case: If a class contains a method with a
1484 free variable that has the same name as a method,
1485 the name will be considered free *and* local in the
1486 class. It should be handled by the closure, as
1487 well as by the normal name loookup logic.
1488 */
1489 reftype = get_ref_type(c, name);
1490 if (reftype == CELL)
1491 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1492 else /* (reftype == FREE) */
1493 arg = compiler_lookup_arg(c->u->u_freevars, name);
1494 if (arg == -1) {
1495 fprintf(stderr,
1496 "lookup %s in %s %d %d\n"
1497 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001498 PyUnicode_AsUTF8(PyObject_Repr(name)),
1499 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001501 PyUnicode_AsUTF8(co->co_name),
1502 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_FatalError("compiler_make_closure()");
1504 }
1505 ADDOP_I(c, LOAD_CLOSURE, arg);
1506 }
1507 ADDOP_I(c, BUILD_TUPLE, free);
1508 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001509 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 ADDOP_I(c, MAKE_CLOSURE, args);
1511 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512}
1513
1514static int
1515compiler_decorators(struct compiler *c, asdl_seq* decos)
1516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (!decos)
1520 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1523 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1524 }
1525 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526}
1527
1528static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001529compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int i, default_count = 0;
1533 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1534 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1535 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1536 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001537 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1538 if (!mangled)
1539 return -1;
1540 ADDOP_O(c, LOAD_CONST, mangled, consts);
1541 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (!compiler_visit_expr(c, default_)) {
1543 return -1;
1544 }
1545 default_count++;
1546 }
1547 }
1548 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001549}
1550
1551static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001552compiler_visit_argannotation(struct compiler *c, identifier id,
1553 expr_ty annotation, PyObject *names)
1554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001556 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001558 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001559 if (!mangled)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 return -1;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001561 if (PyList_Append(names, mangled) < 0) {
1562 Py_DECREF(mangled);
1563 return -1;
1564 }
1565 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 }
1567 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001568}
1569
1570static int
1571compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1572 PyObject *names)
1573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 int i, error;
1575 for (i = 0; i < asdl_seq_LEN(args); i++) {
1576 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1577 error = compiler_visit_argannotation(
1578 c,
1579 arg->arg,
1580 arg->annotation,
1581 names);
1582 if (error)
1583 return error;
1584 }
1585 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001586}
1587
1588static int
1589compiler_visit_annotations(struct compiler *c, arguments_ty args,
1590 expr_ty returns)
1591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* Push arg annotations and a list of the argument names. Return the #
1593 of items pushed. The expressions are evaluated out-of-order wrt the
1594 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1597 */
1598 static identifier return_str;
1599 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001600 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 names = PyList_New(0);
1602 if (!names)
1603 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (compiler_visit_argannotations(c, args->args, names))
1606 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001607 if (args->vararg && args->vararg->annotation &&
1608 compiler_visit_argannotation(c, args->vararg->arg,
1609 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 goto error;
1611 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1612 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001613 if (args->kwarg && args->kwarg->annotation &&
1614 compiler_visit_argannotation(c, args->kwarg->arg,
1615 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (!return_str) {
1619 return_str = PyUnicode_InternFromString("return");
1620 if (!return_str)
1621 goto error;
1622 }
1623 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1624 goto error;
1625 }
1626
1627 len = PyList_GET_SIZE(names);
1628 if (len > 65534) {
1629 /* len must fit in 16 bits, and len is incremented below */
1630 PyErr_SetString(PyExc_SyntaxError,
1631 "too many annotations");
1632 goto error;
1633 }
1634 if (len) {
1635 /* convert names to a tuple and place on stack */
1636 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001637 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 PyObject *s = PyTuple_New(len);
1639 if (!s)
1640 goto error;
1641 for (i = 0; i < len; i++) {
1642 elt = PyList_GET_ITEM(names, i);
1643 Py_INCREF(elt);
1644 PyTuple_SET_ITEM(s, i, elt);
1645 }
1646 ADDOP_O(c, LOAD_CONST, s, consts);
1647 Py_DECREF(s);
1648 len++; /* include the just-pushed tuple */
1649 }
1650 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001651
1652 /* We just checked that len <= 65535, see above */
1653 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001654
1655error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_DECREF(names);
1657 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001658}
1659
1660static int
Yury Selivanov75445082015-05-11 22:57:16 -04001661compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001664 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001665 arguments_ty args;
1666 expr_ty returns;
1667 identifier name;
1668 asdl_seq* decos;
1669 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001671 Py_ssize_t i, n, arglength;
1672 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001674 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
Yury Selivanov75445082015-05-11 22:57:16 -04001676
1677 if (is_async) {
1678 assert(s->kind == AsyncFunctionDef_kind);
1679
1680 args = s->v.AsyncFunctionDef.args;
1681 returns = s->v.AsyncFunctionDef.returns;
1682 decos = s->v.AsyncFunctionDef.decorator_list;
1683 name = s->v.AsyncFunctionDef.name;
1684 body = s->v.AsyncFunctionDef.body;
1685
1686 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1687 } else {
1688 assert(s->kind == FunctionDef_kind);
1689
1690 args = s->v.FunctionDef.args;
1691 returns = s->v.FunctionDef.returns;
1692 decos = s->v.FunctionDef.decorator_list;
1693 name = s->v.FunctionDef.name;
1694 body = s->v.FunctionDef.body;
1695
1696 scope_type = COMPILER_SCOPE_FUNCTION;
1697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (!compiler_decorators(c, decos))
1700 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001701 if (args->defaults)
1702 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (args->kwonlyargs) {
1704 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1705 args->kw_defaults);
1706 if (res < 0)
1707 return 0;
1708 kw_default_count = res;
1709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 num_annotations = compiler_visit_annotations(c, args, returns);
1711 if (num_annotations < 0)
1712 return 0;
1713 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001714
Yury Selivanov75445082015-05-11 22:57:16 -04001715 if (!compiler_enter_scope(c, name,
1716 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 s->lineno))
1718 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001719
Yury Selivanov75445082015-05-11 22:57:16 -04001720 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001722 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 first_const = st->v.Expr.value->v.Str.s;
1724 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1725 compiler_exit_scope(c);
1726 return 0;
1727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 c->u->u_argcount = asdl_seq_LEN(args->args);
1730 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001731 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* if there was a docstring, we need to skip the first statement */
1733 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001734 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 VISIT_IN_SCOPE(c, stmt, st);
1736 }
1737 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001738 qualname = c->u->u_qualname;
1739 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001741 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001742 Py_XDECREF(qualname);
1743 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001745 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 arglength = asdl_seq_LEN(args->defaults);
1748 arglength |= kw_default_count << 8;
1749 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001750 compiler_make_closure(c, co, arglength, qualname);
1751 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001753
Yury Selivanov75445082015-05-11 22:57:16 -04001754 if (is_async) {
1755 co->co_flags |= CO_COROUTINE;
1756 /* An async function is always a generator, even
1757 if there is no 'yield' expressions in it. */
1758 co->co_flags |= CO_GENERATOR;
1759 }
1760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* decorators */
1762 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1763 ADDOP_I(c, CALL_FUNCTION, 1);
1764 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
Yury Selivanov75445082015-05-11 22:57:16 -04001766 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001767}
1768
1769static int
1770compiler_class(struct compiler *c, stmt_ty s)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyCodeObject *co;
1773 PyObject *str;
1774 int i;
1775 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (!compiler_decorators(c, decos))
1778 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* ultimately generate code for:
1781 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1782 where:
1783 <func> is a function/closure created from the class body;
1784 it has a single argument (__locals__) where the dict
1785 (or MutableSequence) representing the locals is passed
1786 <name> is the class name
1787 <bases> is the positional arguments and *varargs argument
1788 <keywords> is the keyword arguments and **kwds argument
1789 This borrows from compiler_call.
1790 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001793 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1794 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 return 0;
1796 /* this block represents what we do in the new scope */
1797 {
1798 /* use the class name for name mangling */
1799 Py_INCREF(s->v.ClassDef.name);
1800 Py_XDECREF(c->u->u_private);
1801 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* load (global) __name__ ... */
1803 str = PyUnicode_InternFromString("__name__");
1804 if (!str || !compiler_nameop(c, str, Load)) {
1805 Py_XDECREF(str);
1806 compiler_exit_scope(c);
1807 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 Py_DECREF(str);
1810 /* ... and store it as __module__ */
1811 str = PyUnicode_InternFromString("__module__");
1812 if (!str || !compiler_nameop(c, str, Store)) {
1813 Py_XDECREF(str);
1814 compiler_exit_scope(c);
1815 return 0;
1816 }
1817 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001818 assert(c->u->u_qualname);
1819 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001820 str = PyUnicode_InternFromString("__qualname__");
1821 if (!str || !compiler_nameop(c, str, Store)) {
1822 Py_XDECREF(str);
1823 compiler_exit_scope(c);
1824 return 0;
1825 }
1826 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 /* compile the body proper */
1828 if (!compiler_body(c, s->v.ClassDef.body)) {
1829 compiler_exit_scope(c);
1830 return 0;
1831 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001832 if (c->u->u_ste->ste_needs_class_closure) {
1833 /* return the (empty) __class__ cell */
1834 str = PyUnicode_InternFromString("__class__");
1835 if (str == NULL) {
1836 compiler_exit_scope(c);
1837 return 0;
1838 }
1839 i = compiler_lookup_arg(c->u->u_cellvars, str);
1840 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001841 if (i < 0) {
1842 compiler_exit_scope(c);
1843 return 0;
1844 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001845 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 /* Return the cell where to store __class__ */
1847 ADDOP_I(c, LOAD_CLOSURE, i);
1848 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001849 else {
1850 assert(PyDict_Size(c->u->u_cellvars) == 0);
1851 /* This happens when nobody references the cell. Return None. */
1852 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1853 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1855 /* create the code object */
1856 co = assemble(c, 1);
1857 }
1858 /* leave the new scope */
1859 compiler_exit_scope(c);
1860 if (co == NULL)
1861 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 /* 2. load the 'build_class' function */
1864 ADDOP(c, LOAD_BUILD_CLASS);
1865
1866 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001867 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 Py_DECREF(co);
1869
1870 /* 4. load class name */
1871 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1872
1873 /* 5. generate the rest of the code for the call */
1874 if (!compiler_call_helper(c, 2,
1875 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001876 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 return 0;
1878
1879 /* 6. apply decorators */
1880 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1881 ADDOP_I(c, CALL_FUNCTION, 1);
1882 }
1883
1884 /* 7. store into <name> */
1885 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1886 return 0;
1887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888}
1889
1890static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001891compiler_ifexp(struct compiler *c, expr_ty e)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 basicblock *end, *next;
1894
1895 assert(e->kind == IfExp_kind);
1896 end = compiler_new_block(c);
1897 if (end == NULL)
1898 return 0;
1899 next = compiler_new_block(c);
1900 if (next == NULL)
1901 return 0;
1902 VISIT(c, expr, e->v.IfExp.test);
1903 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1904 VISIT(c, expr, e->v.IfExp.body);
1905 ADDOP_JREL(c, JUMP_FORWARD, end);
1906 compiler_use_next_block(c, next);
1907 VISIT(c, expr, e->v.IfExp.orelse);
1908 compiler_use_next_block(c, end);
1909 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001910}
1911
1912static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913compiler_lambda(struct compiler *c, expr_ty e)
1914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001916 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001918 int kw_default_count = 0;
1919 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 arguments_ty args = e->v.Lambda.args;
1921 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (!name) {
1924 name = PyUnicode_InternFromString("<lambda>");
1925 if (!name)
1926 return 0;
1927 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001929 if (args->defaults)
1930 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 if (args->kwonlyargs) {
1932 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1933 args->kw_defaults);
1934 if (res < 0) return 0;
1935 kw_default_count = res;
1936 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001937 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001938 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* Make None the first constant, so the lambda can't have a
1942 docstring. */
1943 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1944 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 c->u->u_argcount = asdl_seq_LEN(args->args);
1947 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1948 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1949 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001950 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
1952 else {
1953 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001954 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001956 qualname = c->u->u_qualname;
1957 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001959 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 arglength = asdl_seq_LEN(args->defaults);
1963 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001964 compiler_make_closure(c, co, arglength, qualname);
1965 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 Py_DECREF(co);
1967
1968 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969}
1970
1971static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972compiler_if(struct compiler *c, stmt_ty s)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 basicblock *end, *next;
1975 int constant;
1976 assert(s->kind == If_kind);
1977 end = compiler_new_block(c);
1978 if (end == NULL)
1979 return 0;
1980
Georg Brandl8334fd92010-12-04 10:26:46 +00001981 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* constant = 0: "if 0"
1983 * constant = 1: "if 1", "if 2", ...
1984 * constant = -1: rest */
1985 if (constant == 0) {
1986 if (s->v.If.orelse)
1987 VISIT_SEQ(c, stmt, s->v.If.orelse);
1988 } else if (constant == 1) {
1989 VISIT_SEQ(c, stmt, s->v.If.body);
1990 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001991 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 next = compiler_new_block(c);
1993 if (next == NULL)
1994 return 0;
1995 }
1996 else
1997 next = end;
1998 VISIT(c, expr, s->v.If.test);
1999 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2000 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002001 if (asdl_seq_LEN(s->v.If.orelse)) {
2002 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 compiler_use_next_block(c, next);
2004 VISIT_SEQ(c, stmt, s->v.If.orelse);
2005 }
2006 }
2007 compiler_use_next_block(c, end);
2008 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009}
2010
2011static int
2012compiler_for(struct compiler *c, stmt_ty s)
2013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 start = compiler_new_block(c);
2017 cleanup = compiler_new_block(c);
2018 end = compiler_new_block(c);
2019 if (start == NULL || end == NULL || cleanup == NULL)
2020 return 0;
2021 ADDOP_JREL(c, SETUP_LOOP, end);
2022 if (!compiler_push_fblock(c, LOOP, start))
2023 return 0;
2024 VISIT(c, expr, s->v.For.iter);
2025 ADDOP(c, GET_ITER);
2026 compiler_use_next_block(c, start);
2027 ADDOP_JREL(c, FOR_ITER, cleanup);
2028 VISIT(c, expr, s->v.For.target);
2029 VISIT_SEQ(c, stmt, s->v.For.body);
2030 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2031 compiler_use_next_block(c, cleanup);
2032 ADDOP(c, POP_BLOCK);
2033 compiler_pop_fblock(c, LOOP, start);
2034 VISIT_SEQ(c, stmt, s->v.For.orelse);
2035 compiler_use_next_block(c, end);
2036 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037}
2038
Yury Selivanov75445082015-05-11 22:57:16 -04002039
2040static int
2041compiler_async_for(struct compiler *c, stmt_ty s)
2042{
2043 static PyObject *stopiter_error = NULL;
2044 basicblock *try, *except, *end, *after_try, *try_cleanup,
2045 *after_loop, *after_loop_else;
2046
2047 if (stopiter_error == NULL) {
2048 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2049 if (stopiter_error == NULL)
2050 return 0;
2051 }
2052
2053 try = compiler_new_block(c);
2054 except = compiler_new_block(c);
2055 end = compiler_new_block(c);
2056 after_try = compiler_new_block(c);
2057 try_cleanup = compiler_new_block(c);
2058 after_loop = compiler_new_block(c);
2059 after_loop_else = compiler_new_block(c);
2060
2061 if (try == NULL || except == NULL || end == NULL
2062 || after_try == NULL || try_cleanup == NULL)
2063 return 0;
2064
2065 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2066 if (!compiler_push_fblock(c, LOOP, try))
2067 return 0;
2068
2069 VISIT(c, expr, s->v.AsyncFor.iter);
2070 ADDOP(c, GET_AITER);
2071 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2072 ADDOP(c, YIELD_FROM);
2073
2074 compiler_use_next_block(c, try);
2075
2076
2077 ADDOP_JREL(c, SETUP_EXCEPT, except);
2078 if (!compiler_push_fblock(c, EXCEPT, try))
2079 return 0;
2080
2081 ADDOP(c, GET_ANEXT);
2082 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2083 ADDOP(c, YIELD_FROM);
2084 VISIT(c, expr, s->v.AsyncFor.target);
2085 ADDOP(c, POP_BLOCK);
2086 compiler_pop_fblock(c, EXCEPT, try);
2087 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2088
2089
2090 compiler_use_next_block(c, except);
2091 ADDOP(c, DUP_TOP);
2092 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2093 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2094 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2095
2096 ADDOP(c, POP_TOP);
2097 ADDOP(c, POP_TOP);
2098 ADDOP(c, POP_TOP);
2099 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2100 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2101 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2102
2103
2104 compiler_use_next_block(c, try_cleanup);
2105 ADDOP(c, END_FINALLY);
2106
2107 compiler_use_next_block(c, after_try);
2108 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2109 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2110
2111 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2112 compiler_pop_fblock(c, LOOP, try);
2113
2114 compiler_use_next_block(c, after_loop);
2115 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2116
2117 compiler_use_next_block(c, after_loop_else);
2118 VISIT_SEQ(c, stmt, s->v.For.orelse);
2119
2120 compiler_use_next_block(c, end);
2121
2122 return 1;
2123}
2124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125static int
2126compiler_while(struct compiler *c, stmt_ty s)
2127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002129 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (constant == 0) {
2132 if (s->v.While.orelse)
2133 VISIT_SEQ(c, stmt, s->v.While.orelse);
2134 return 1;
2135 }
2136 loop = compiler_new_block(c);
2137 end = compiler_new_block(c);
2138 if (constant == -1) {
2139 anchor = compiler_new_block(c);
2140 if (anchor == NULL)
2141 return 0;
2142 }
2143 if (loop == NULL || end == NULL)
2144 return 0;
2145 if (s->v.While.orelse) {
2146 orelse = compiler_new_block(c);
2147 if (orelse == NULL)
2148 return 0;
2149 }
2150 else
2151 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 ADDOP_JREL(c, SETUP_LOOP, end);
2154 compiler_use_next_block(c, loop);
2155 if (!compiler_push_fblock(c, LOOP, loop))
2156 return 0;
2157 if (constant == -1) {
2158 VISIT(c, expr, s->v.While.test);
2159 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2160 }
2161 VISIT_SEQ(c, stmt, s->v.While.body);
2162 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* XXX should the two POP instructions be in a separate block
2165 if there is no else clause ?
2166 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002168 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002170 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 compiler_pop_fblock(c, LOOP, loop);
2172 if (orelse != NULL) /* what if orelse is just pass? */
2173 VISIT_SEQ(c, stmt, s->v.While.orelse);
2174 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177}
2178
2179static int
2180compiler_continue(struct compiler *c)
2181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2183 static const char IN_FINALLY_ERROR_MSG[] =
2184 "'continue' not supported inside 'finally' clause";
2185 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (!c->u->u_nfblocks)
2188 return compiler_error(c, LOOP_ERROR_MSG);
2189 i = c->u->u_nfblocks - 1;
2190 switch (c->u->u_fblock[i].fb_type) {
2191 case LOOP:
2192 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2193 break;
2194 case EXCEPT:
2195 case FINALLY_TRY:
2196 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2197 /* Prevent continue anywhere under a finally
2198 even if hidden in a sub-try or except. */
2199 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2200 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2201 }
2202 if (i == -1)
2203 return compiler_error(c, LOOP_ERROR_MSG);
2204 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2205 break;
2206 case FINALLY_END:
2207 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211}
2212
2213/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214
2215 SETUP_FINALLY L
2216 <code for body>
2217 POP_BLOCK
2218 LOAD_CONST <None>
2219 L: <code for finalbody>
2220 END_FINALLY
2221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222 The special instructions use the block stack. Each block
2223 stack entry contains the instruction that created it (here
2224 SETUP_FINALLY), the level of the value stack at the time the
2225 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 Pushes the current value stack level and the label
2229 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002230 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 Pops en entry from the block stack, and pops the value
2232 stack until its level is the same as indicated on the
2233 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 Pops a variable number of entries from the *value* stack
2236 and re-raises the exception they specify. The number of
2237 entries popped depends on the (pseudo) exception type.
2238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239 The block stack is unwound when an exception is raised:
2240 when a SETUP_FINALLY entry is found, the exception is pushed
2241 onto the value stack (and the exception condition is cleared),
2242 and the interpreter jumps to the label gotten from the block
2243 stack.
2244*/
2245
2246static int
2247compiler_try_finally(struct compiler *c, stmt_ty s)
2248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 basicblock *body, *end;
2250 body = compiler_new_block(c);
2251 end = compiler_new_block(c);
2252 if (body == NULL || end == NULL)
2253 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 ADDOP_JREL(c, SETUP_FINALLY, end);
2256 compiler_use_next_block(c, body);
2257 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2258 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002259 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2260 if (!compiler_try_except(c, s))
2261 return 0;
2262 }
2263 else {
2264 VISIT_SEQ(c, stmt, s->v.Try.body);
2265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 ADDOP(c, POP_BLOCK);
2267 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2270 compiler_use_next_block(c, end);
2271 if (!compiler_push_fblock(c, FINALLY_END, end))
2272 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002273 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 ADDOP(c, END_FINALLY);
2275 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278}
2279
2280/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002281 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 (The contents of the value stack is shown in [], with the top
2283 at the right; 'tb' is trace-back info, 'val' the exception's
2284 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285
2286 Value stack Label Instruction Argument
2287 [] SETUP_EXCEPT L1
2288 [] <code for S>
2289 [] POP_BLOCK
2290 [] JUMP_FORWARD L0
2291
2292 [tb, val, exc] L1: DUP )
2293 [tb, val, exc, exc] <evaluate E1> )
2294 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2295 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2296 [tb, val, exc] POP
2297 [tb, val] <assign to V1> (or POP if no V1)
2298 [tb] POP
2299 [] <code for S1>
2300 JUMP_FORWARD L0
2301
2302 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 .............................etc.......................
2304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2306
2307 [] L0: <next statement>
2308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 Of course, parts are not generated if Vi or Ei is not present.
2310*/
2311static int
2312compiler_try_except(struct compiler *c, stmt_ty s)
2313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002315 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 body = compiler_new_block(c);
2318 except = compiler_new_block(c);
2319 orelse = compiler_new_block(c);
2320 end = compiler_new_block(c);
2321 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2322 return 0;
2323 ADDOP_JREL(c, SETUP_EXCEPT, except);
2324 compiler_use_next_block(c, body);
2325 if (!compiler_push_fblock(c, EXCEPT, body))
2326 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002327 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 ADDOP(c, POP_BLOCK);
2329 compiler_pop_fblock(c, EXCEPT, body);
2330 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002331 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 compiler_use_next_block(c, except);
2333 for (i = 0; i < n; i++) {
2334 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002335 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (!handler->v.ExceptHandler.type && i < n-1)
2337 return compiler_error(c, "default 'except:' must be last");
2338 c->u->u_lineno_set = 0;
2339 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002340 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 except = compiler_new_block(c);
2342 if (except == NULL)
2343 return 0;
2344 if (handler->v.ExceptHandler.type) {
2345 ADDOP(c, DUP_TOP);
2346 VISIT(c, expr, handler->v.ExceptHandler.type);
2347 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2348 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2349 }
2350 ADDOP(c, POP_TOP);
2351 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002352 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002353
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002354 cleanup_end = compiler_new_block(c);
2355 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002356 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002357 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002358
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002359 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2360 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002362 /*
2363 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002364 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002365 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002366 try:
2367 # body
2368 finally:
2369 name = None
2370 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002371 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002373 /* second try: */
2374 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2375 compiler_use_next_block(c, cleanup_body);
2376 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2377 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002379 /* second # body */
2380 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2381 ADDOP(c, POP_BLOCK);
2382 ADDOP(c, POP_EXCEPT);
2383 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002385 /* finally: */
2386 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2387 compiler_use_next_block(c, cleanup_end);
2388 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2389 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002391 /* name = None */
2392 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2393 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002395 /* del name */
2396 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002398 ADDOP(c, END_FINALLY);
2399 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 }
2401 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002402 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002404 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002405 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002406 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407
Guido van Rossumb940e112007-01-10 16:19:56 +00002408 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002409 ADDOP(c, POP_TOP);
2410 compiler_use_next_block(c, cleanup_body);
2411 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2412 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002414 ADDOP(c, POP_EXCEPT);
2415 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 }
2417 ADDOP_JREL(c, JUMP_FORWARD, end);
2418 compiler_use_next_block(c, except);
2419 }
2420 ADDOP(c, END_FINALLY);
2421 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002422 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 compiler_use_next_block(c, end);
2424 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425}
2426
2427static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002428compiler_try(struct compiler *c, stmt_ty s) {
2429 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2430 return compiler_try_finally(c, s);
2431 else
2432 return compiler_try_except(c, s);
2433}
2434
2435
2436static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437compiler_import_as(struct compiler *c, identifier name, identifier asname)
2438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* The IMPORT_NAME opcode was already generated. This function
2440 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 If there is a dot in name, we need to split it and emit a
2443 LOAD_ATTR for each name.
2444 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002445 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2446 PyUnicode_GET_LENGTH(name), 1);
2447 if (dot == -2)
2448 return -1;
2449 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 Py_ssize_t pos = dot + 1;
2452 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 dot = PyUnicode_FindChar(name, '.', pos,
2455 PyUnicode_GET_LENGTH(name), 1);
2456 if (dot == -2)
2457 return -1;
2458 attr = PyUnicode_Substring(name, pos,
2459 (dot != -1) ? dot :
2460 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (!attr)
2462 return -1;
2463 ADDOP_O(c, LOAD_ATTR, attr, names);
2464 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002465 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 }
2467 }
2468 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469}
2470
2471static int
2472compiler_import(struct compiler *c, stmt_ty s)
2473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* The Import node stores a module name like a.b.c as a single
2475 string. This is convenient for all cases except
2476 import a.b.c as d
2477 where we need to parse that string to extract the individual
2478 module names.
2479 XXX Perhaps change the representation to make this case simpler?
2480 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002481 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 for (i = 0; i < n; i++) {
2484 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2485 int r;
2486 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 level = PyLong_FromLong(0);
2489 if (level == NULL)
2490 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 ADDOP_O(c, LOAD_CONST, level, consts);
2493 Py_DECREF(level);
2494 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2495 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 if (alias->asname) {
2498 r = compiler_import_as(c, alias->name, alias->asname);
2499 if (!r)
2500 return r;
2501 }
2502 else {
2503 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 Py_ssize_t dot = PyUnicode_FindChar(
2505 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002506 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002508 if (tmp == NULL)
2509 return 0;
2510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 Py_DECREF(tmp);
2514 }
2515 if (!r)
2516 return r;
2517 }
2518 }
2519 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520}
2521
2522static int
2523compiler_from_import(struct compiler *c, stmt_ty s)
2524{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002525 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 PyObject *names = PyTuple_New(n);
2528 PyObject *level;
2529 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (!empty_string) {
2532 empty_string = PyUnicode_FromString("");
2533 if (!empty_string)
2534 return 0;
2535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (!names)
2538 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 level = PyLong_FromLong(s->v.ImportFrom.level);
2541 if (!level) {
2542 Py_DECREF(names);
2543 return 0;
2544 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* build up the names */
2547 for (i = 0; i < n; i++) {
2548 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2549 Py_INCREF(alias->name);
2550 PyTuple_SET_ITEM(names, i, alias->name);
2551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2554 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2555 Py_DECREF(level);
2556 Py_DECREF(names);
2557 return compiler_error(c, "from __future__ imports must occur "
2558 "at the beginning of the file");
2559 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 ADDOP_O(c, LOAD_CONST, level, consts);
2562 Py_DECREF(level);
2563 ADDOP_O(c, LOAD_CONST, names, consts);
2564 Py_DECREF(names);
2565 if (s->v.ImportFrom.module) {
2566 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2567 }
2568 else {
2569 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2570 }
2571 for (i = 0; i < n; i++) {
2572 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2573 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002575 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 assert(n == 1);
2577 ADDOP(c, IMPORT_STAR);
2578 return 1;
2579 }
2580
2581 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2582 store_name = alias->name;
2583 if (alias->asname)
2584 store_name = alias->asname;
2585
2586 if (!compiler_nameop(c, store_name, Store)) {
2587 Py_DECREF(names);
2588 return 0;
2589 }
2590 }
2591 /* remove imported module */
2592 ADDOP(c, POP_TOP);
2593 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594}
2595
2596static int
2597compiler_assert(struct compiler *c, stmt_ty s)
2598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 static PyObject *assertion_error = NULL;
2600 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002601 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602
Georg Brandl8334fd92010-12-04 10:26:46 +00002603 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 return 1;
2605 if (assertion_error == NULL) {
2606 assertion_error = PyUnicode_InternFromString("AssertionError");
2607 if (assertion_error == NULL)
2608 return 0;
2609 }
2610 if (s->v.Assert.test->kind == Tuple_kind &&
2611 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002612 msg = PyUnicode_FromString("assertion is always true, "
2613 "perhaps remove parentheses?");
2614 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002616 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2617 c->c_filename, c->u->u_lineno,
2618 NULL, NULL) == -1) {
2619 Py_DECREF(msg);
2620 return 0;
2621 }
2622 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 }
2624 VISIT(c, expr, s->v.Assert.test);
2625 end = compiler_new_block(c);
2626 if (end == NULL)
2627 return 0;
2628 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2629 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2630 if (s->v.Assert.msg) {
2631 VISIT(c, expr, s->v.Assert.msg);
2632 ADDOP_I(c, CALL_FUNCTION, 1);
2633 }
2634 ADDOP_I(c, RAISE_VARARGS, 1);
2635 compiler_use_next_block(c, end);
2636 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637}
2638
2639static int
2640compiler_visit_stmt(struct compiler *c, stmt_ty s)
2641{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002642 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* Always assign a lineno to the next instruction for a stmt. */
2645 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002646 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 switch (s->kind) {
2650 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002651 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 case ClassDef_kind:
2653 return compiler_class(c, s);
2654 case Return_kind:
2655 if (c->u->u_ste->ste_type != FunctionBlock)
2656 return compiler_error(c, "'return' outside function");
2657 if (s->v.Return.value) {
2658 VISIT(c, expr, s->v.Return.value);
2659 }
2660 else
2661 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2662 ADDOP(c, RETURN_VALUE);
2663 break;
2664 case Delete_kind:
2665 VISIT_SEQ(c, expr, s->v.Delete.targets)
2666 break;
2667 case Assign_kind:
2668 n = asdl_seq_LEN(s->v.Assign.targets);
2669 VISIT(c, expr, s->v.Assign.value);
2670 for (i = 0; i < n; i++) {
2671 if (i < n - 1)
2672 ADDOP(c, DUP_TOP);
2673 VISIT(c, expr,
2674 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2675 }
2676 break;
2677 case AugAssign_kind:
2678 return compiler_augassign(c, s);
2679 case For_kind:
2680 return compiler_for(c, s);
2681 case While_kind:
2682 return compiler_while(c, s);
2683 case If_kind:
2684 return compiler_if(c, s);
2685 case Raise_kind:
2686 n = 0;
2687 if (s->v.Raise.exc) {
2688 VISIT(c, expr, s->v.Raise.exc);
2689 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002690 if (s->v.Raise.cause) {
2691 VISIT(c, expr, s->v.Raise.cause);
2692 n++;
2693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002695 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002697 case Try_kind:
2698 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 case Assert_kind:
2700 return compiler_assert(c, s);
2701 case Import_kind:
2702 return compiler_import(c, s);
2703 case ImportFrom_kind:
2704 return compiler_from_import(c, s);
2705 case Global_kind:
2706 case Nonlocal_kind:
2707 break;
2708 case Expr_kind:
2709 if (c->c_interactive && c->c_nestlevel <= 1) {
2710 VISIT(c, expr, s->v.Expr.value);
2711 ADDOP(c, PRINT_EXPR);
2712 }
2713 else if (s->v.Expr.value->kind != Str_kind &&
2714 s->v.Expr.value->kind != Num_kind) {
2715 VISIT(c, expr, s->v.Expr.value);
2716 ADDOP(c, POP_TOP);
2717 }
2718 break;
2719 case Pass_kind:
2720 break;
2721 case Break_kind:
2722 if (!compiler_in_loop(c))
2723 return compiler_error(c, "'break' outside loop");
2724 ADDOP(c, BREAK_LOOP);
2725 break;
2726 case Continue_kind:
2727 return compiler_continue(c);
2728 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002729 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002730 case AsyncFunctionDef_kind:
2731 return compiler_function(c, s, 1);
2732 case AsyncWith_kind:
2733 return compiler_async_with(c, s, 0);
2734 case AsyncFor_kind:
2735 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 }
Yury Selivanov75445082015-05-11 22:57:16 -04002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739}
2740
2741static int
2742unaryop(unaryop_ty op)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 switch (op) {
2745 case Invert:
2746 return UNARY_INVERT;
2747 case Not:
2748 return UNARY_NOT;
2749 case UAdd:
2750 return UNARY_POSITIVE;
2751 case USub:
2752 return UNARY_NEGATIVE;
2753 default:
2754 PyErr_Format(PyExc_SystemError,
2755 "unary op %d should not be possible", op);
2756 return 0;
2757 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758}
2759
2760static int
2761binop(struct compiler *c, operator_ty op)
2762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 switch (op) {
2764 case Add:
2765 return BINARY_ADD;
2766 case Sub:
2767 return BINARY_SUBTRACT;
2768 case Mult:
2769 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002770 case MatMult:
2771 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 case Div:
2773 return BINARY_TRUE_DIVIDE;
2774 case Mod:
2775 return BINARY_MODULO;
2776 case Pow:
2777 return BINARY_POWER;
2778 case LShift:
2779 return BINARY_LSHIFT;
2780 case RShift:
2781 return BINARY_RSHIFT;
2782 case BitOr:
2783 return BINARY_OR;
2784 case BitXor:
2785 return BINARY_XOR;
2786 case BitAnd:
2787 return BINARY_AND;
2788 case FloorDiv:
2789 return BINARY_FLOOR_DIVIDE;
2790 default:
2791 PyErr_Format(PyExc_SystemError,
2792 "binary op %d should not be possible", op);
2793 return 0;
2794 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795}
2796
2797static int
2798cmpop(cmpop_ty op)
2799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 switch (op) {
2801 case Eq:
2802 return PyCmp_EQ;
2803 case NotEq:
2804 return PyCmp_NE;
2805 case Lt:
2806 return PyCmp_LT;
2807 case LtE:
2808 return PyCmp_LE;
2809 case Gt:
2810 return PyCmp_GT;
2811 case GtE:
2812 return PyCmp_GE;
2813 case Is:
2814 return PyCmp_IS;
2815 case IsNot:
2816 return PyCmp_IS_NOT;
2817 case In:
2818 return PyCmp_IN;
2819 case NotIn:
2820 return PyCmp_NOT_IN;
2821 default:
2822 return PyCmp_BAD;
2823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824}
2825
2826static int
2827inplace_binop(struct compiler *c, operator_ty op)
2828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 switch (op) {
2830 case Add:
2831 return INPLACE_ADD;
2832 case Sub:
2833 return INPLACE_SUBTRACT;
2834 case Mult:
2835 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002836 case MatMult:
2837 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 case Div:
2839 return INPLACE_TRUE_DIVIDE;
2840 case Mod:
2841 return INPLACE_MODULO;
2842 case Pow:
2843 return INPLACE_POWER;
2844 case LShift:
2845 return INPLACE_LSHIFT;
2846 case RShift:
2847 return INPLACE_RSHIFT;
2848 case BitOr:
2849 return INPLACE_OR;
2850 case BitXor:
2851 return INPLACE_XOR;
2852 case BitAnd:
2853 return INPLACE_AND;
2854 case FloorDiv:
2855 return INPLACE_FLOOR_DIVIDE;
2856 default:
2857 PyErr_Format(PyExc_SystemError,
2858 "inplace binary op %d should not be possible", op);
2859 return 0;
2860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861}
2862
2863static int
2864compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2865{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002866 int op, scope;
2867 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 PyObject *dict = c->u->u_names;
2871 PyObject *mangled;
2872 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 mangled = _Py_Mangle(c->u->u_private, name);
2875 if (!mangled)
2876 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002877
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002878 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2879 PyUnicode_CompareWithASCIIString(name, "True") &&
2880 PyUnicode_CompareWithASCIIString(name, "False"));
2881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 op = 0;
2883 optype = OP_NAME;
2884 scope = PyST_GetScope(c->u->u_ste, mangled);
2885 switch (scope) {
2886 case FREE:
2887 dict = c->u->u_freevars;
2888 optype = OP_DEREF;
2889 break;
2890 case CELL:
2891 dict = c->u->u_cellvars;
2892 optype = OP_DEREF;
2893 break;
2894 case LOCAL:
2895 if (c->u->u_ste->ste_type == FunctionBlock)
2896 optype = OP_FAST;
2897 break;
2898 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002899 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 optype = OP_GLOBAL;
2901 break;
2902 case GLOBAL_EXPLICIT:
2903 optype = OP_GLOBAL;
2904 break;
2905 default:
2906 /* scope can be 0 */
2907 break;
2908 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002911 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 switch (optype) {
2914 case OP_DEREF:
2915 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002916 case Load:
2917 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2918 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 case Store: op = STORE_DEREF; break;
2920 case AugLoad:
2921 case AugStore:
2922 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002923 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 case Param:
2925 default:
2926 PyErr_SetString(PyExc_SystemError,
2927 "param invalid for deref variable");
2928 return 0;
2929 }
2930 break;
2931 case OP_FAST:
2932 switch (ctx) {
2933 case Load: op = LOAD_FAST; break;
2934 case Store: op = STORE_FAST; break;
2935 case Del: op = DELETE_FAST; break;
2936 case AugLoad:
2937 case AugStore:
2938 break;
2939 case Param:
2940 default:
2941 PyErr_SetString(PyExc_SystemError,
2942 "param invalid for local variable");
2943 return 0;
2944 }
2945 ADDOP_O(c, op, mangled, varnames);
2946 Py_DECREF(mangled);
2947 return 1;
2948 case OP_GLOBAL:
2949 switch (ctx) {
2950 case Load: op = LOAD_GLOBAL; break;
2951 case Store: op = STORE_GLOBAL; break;
2952 case Del: op = DELETE_GLOBAL; break;
2953 case AugLoad:
2954 case AugStore:
2955 break;
2956 case Param:
2957 default:
2958 PyErr_SetString(PyExc_SystemError,
2959 "param invalid for global variable");
2960 return 0;
2961 }
2962 break;
2963 case OP_NAME:
2964 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002965 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 case Store: op = STORE_NAME; break;
2967 case Del: op = DELETE_NAME; break;
2968 case AugLoad:
2969 case AugStore:
2970 break;
2971 case Param:
2972 default:
2973 PyErr_SetString(PyExc_SystemError,
2974 "param invalid for name variable");
2975 return 0;
2976 }
2977 break;
2978 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 assert(op);
2981 arg = compiler_add_o(c, dict, mangled);
2982 Py_DECREF(mangled);
2983 if (arg < 0)
2984 return 0;
2985 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986}
2987
2988static int
2989compiler_boolop(struct compiler *c, expr_ty e)
2990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002992 int jumpi;
2993 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 assert(e->kind == BoolOp_kind);
2997 if (e->v.BoolOp.op == And)
2998 jumpi = JUMP_IF_FALSE_OR_POP;
2999 else
3000 jumpi = JUMP_IF_TRUE_OR_POP;
3001 end = compiler_new_block(c);
3002 if (end == NULL)
3003 return 0;
3004 s = e->v.BoolOp.values;
3005 n = asdl_seq_LEN(s) - 1;
3006 assert(n >= 0);
3007 for (i = 0; i < n; ++i) {
3008 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3009 ADDOP_JABS(c, jumpi, end);
3010 }
3011 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3012 compiler_use_next_block(c, end);
3013 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014}
3015
3016static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003017starunpack_helper(struct compiler *c, asdl_seq *elts,
3018 int single_op, int inner_op, int outer_op)
3019{
3020 Py_ssize_t n = asdl_seq_LEN(elts);
3021 Py_ssize_t i, nsubitems = 0, nseen = 0;
3022 for (i = 0; i < n; i++) {
3023 expr_ty elt = asdl_seq_GET(elts, i);
3024 if (elt->kind == Starred_kind) {
3025 if (nseen) {
3026 ADDOP_I(c, inner_op, nseen);
3027 nseen = 0;
3028 nsubitems++;
3029 }
3030 VISIT(c, expr, elt->v.Starred.value);
3031 nsubitems++;
3032 }
3033 else {
3034 VISIT(c, expr, elt);
3035 nseen++;
3036 }
3037 }
3038 if (nsubitems) {
3039 if (nseen) {
3040 ADDOP_I(c, inner_op, nseen);
3041 nsubitems++;
3042 }
3043 ADDOP_I(c, outer_op, nsubitems);
3044 }
3045 else
3046 ADDOP_I(c, single_op, nseen);
3047 return 1;
3048}
3049
3050static int
3051assignment_helper(struct compiler *c, asdl_seq *elts)
3052{
3053 Py_ssize_t n = asdl_seq_LEN(elts);
3054 Py_ssize_t i;
3055 int seen_star = 0;
3056 for (i = 0; i < n; i++) {
3057 expr_ty elt = asdl_seq_GET(elts, i);
3058 if (elt->kind == Starred_kind && !seen_star) {
3059 if ((i >= (1 << 8)) ||
3060 (n-i-1 >= (INT_MAX >> 8)))
3061 return compiler_error(c,
3062 "too many expressions in "
3063 "star-unpacking assignment");
3064 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3065 seen_star = 1;
3066 asdl_seq_SET(elts, i, elt->v.Starred.value);
3067 }
3068 else if (elt->kind == Starred_kind) {
3069 return compiler_error(c,
3070 "two starred expressions in assignment");
3071 }
3072 }
3073 if (!seen_star) {
3074 ADDOP_I(c, UNPACK_SEQUENCE, n);
3075 }
3076 VISIT_SEQ(c, expr, elts);
3077 return 1;
3078}
3079
3080static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003081compiler_list(struct compiler *c, expr_ty e)
3082{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003083 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003085 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003087 else if (e->v.List.ctx == Load) {
3088 return starunpack_helper(c, elts,
3089 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003091 else
3092 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094}
3095
3096static int
3097compiler_tuple(struct compiler *c, expr_ty e)
3098{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003099 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003101 return assignment_helper(c, elts);
3102 }
3103 else if (e->v.Tuple.ctx == Load) {
3104 return starunpack_helper(c, elts,
3105 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3106 }
3107 else
3108 VISIT_SEQ(c, expr, elts);
3109 return 1;
3110}
3111
3112static int
3113compiler_set(struct compiler *c, expr_ty e)
3114{
3115 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3116 BUILD_SET, BUILD_SET_UNPACK);
3117}
3118
3119static int
3120compiler_dict(struct compiler *c, expr_ty e)
3121{
3122 Py_ssize_t i, n, containers, elements;
3123 int is_unpacking = 0;
3124 n = asdl_seq_LEN(e->v.Dict.values);
3125 containers = 0;
3126 elements = 0;
3127 for (i = 0; i < n; i++) {
3128 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3129 if (elements == 0xFFFF || (elements && is_unpacking)) {
3130 ADDOP_I(c, BUILD_MAP, elements);
3131 containers++;
3132 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003134 if (is_unpacking) {
3135 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3136 containers++;
3137 }
3138 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003139 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003140 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003141 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 }
3143 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003144 if (elements || containers == 0) {
3145 ADDOP_I(c, BUILD_MAP, elements);
3146 containers++;
3147 }
3148 /* If there is more than one dict, they need to be merged into a new
3149 * dict. If there is one dict and it's an unpacking, then it needs
3150 * to be copied into a new dict." */
3151 while (containers > 1 || is_unpacking) {
3152 int oparg = containers < 255 ? containers : 255;
3153 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3154 containers -= (oparg - 1);
3155 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
3157 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158}
3159
3160static int
3161compiler_compare(struct compiler *c, expr_ty e)
3162{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003163 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3167 VISIT(c, expr, e->v.Compare.left);
3168 n = asdl_seq_LEN(e->v.Compare.ops);
3169 assert(n > 0);
3170 if (n > 1) {
3171 cleanup = compiler_new_block(c);
3172 if (cleanup == NULL)
3173 return 0;
3174 VISIT(c, expr,
3175 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3176 }
3177 for (i = 1; i < n; i++) {
3178 ADDOP(c, DUP_TOP);
3179 ADDOP(c, ROT_THREE);
3180 ADDOP_I(c, COMPARE_OP,
3181 cmpop((cmpop_ty)(asdl_seq_GET(
3182 e->v.Compare.ops, i - 1))));
3183 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3184 NEXT_BLOCK(c);
3185 if (i < (n - 1))
3186 VISIT(c, expr,
3187 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3188 }
3189 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3190 ADDOP_I(c, COMPARE_OP,
3191 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3192 if (n > 1) {
3193 basicblock *end = compiler_new_block(c);
3194 if (end == NULL)
3195 return 0;
3196 ADDOP_JREL(c, JUMP_FORWARD, end);
3197 compiler_use_next_block(c, cleanup);
3198 ADDOP(c, ROT_TWO);
3199 ADDOP(c, POP_TOP);
3200 compiler_use_next_block(c, end);
3201 }
3202 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203}
3204
3205static int
3206compiler_call(struct compiler *c, expr_ty e)
3207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 VISIT(c, expr, e->v.Call.func);
3209 return compiler_call_helper(c, 0,
3210 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003211 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003212}
3213
3214/* shared code between compiler_call and compiler_class */
3215static int
3216compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003217 Py_ssize_t n, /* Args already pushed */
3218 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003219 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003222 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003223
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003224 /* the number of tuples and dictionaries on the stack */
3225 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3226
3227 nkw = 0;
3228 nseen = 0; /* the number of positional arguments on the stack */
3229 nelts = asdl_seq_LEN(args);
3230 for (i = 0; i < nelts; i++) {
3231 expr_ty elt = asdl_seq_GET(args, i);
3232 if (elt->kind == Starred_kind) {
3233 /* A star-arg. If we've seen positional arguments,
3234 pack the positional arguments into a
3235 tuple. */
3236 if (nseen) {
3237 ADDOP_I(c, BUILD_TUPLE, nseen);
3238 nseen = 0;
3239 nsubargs++;
3240 }
3241 VISIT(c, expr, elt->v.Starred.value);
3242 nsubargs++;
3243 }
3244 else if (nsubargs) {
3245 /* We've seen star-args already, so we
3246 count towards items-to-pack-into-tuple. */
3247 VISIT(c, expr, elt);
3248 nseen++;
3249 }
3250 else {
3251 /* Positional arguments before star-arguments
3252 are left on the stack. */
3253 VISIT(c, expr, elt);
3254 n++;
3255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003257 if (nseen) {
3258 /* Pack up any trailing positional arguments. */
3259 ADDOP_I(c, BUILD_TUPLE, nseen);
3260 nsubargs++;
3261 }
3262 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003264 if (nsubargs > 1) {
3265 /* If we ended up with more than one stararg, we need
3266 to concatenate them into a single sequence. */
3267 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003270
3271 /* Same dance again for keyword arguments */
3272 nseen = 0; /* the number of keyword arguments on the stack following */
3273 nelts = asdl_seq_LEN(keywords);
3274 for (i = 0; i < nelts; i++) {
3275 keyword_ty kw = asdl_seq_GET(keywords, i);
3276 if (kw->arg == NULL) {
3277 /* A keyword argument unpacking. */
3278 if (nseen) {
3279 ADDOP_I(c, BUILD_MAP, nseen);
3280 nseen = 0;
3281 nsubkwargs++;
3282 }
3283 VISIT(c, expr, kw->value);
3284 nsubkwargs++;
3285 }
3286 else if (nsubkwargs) {
3287 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003288 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003289 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003290 nseen++;
3291 }
3292 else {
3293 /* keyword argument */
3294 VISIT(c, keyword, kw)
3295 nkw++;
3296 }
3297 }
3298 if (nseen) {
3299 /* Pack up any trailing keyword arguments. */
3300 ADDOP_I(c, BUILD_MAP, nseen);
3301 nsubkwargs++;
3302 }
3303 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003305 if (nsubkwargs > 1) {
3306 /* Pack it all up */
3307 int function_pos = n + (code & 1) + nkw + 1;
3308 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3309 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003311 assert(n < 1<<8);
3312 assert(nkw < 1<<24);
3313 n |= nkw << 8;
3314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 switch (code) {
3316 case 0:
3317 ADDOP_I(c, CALL_FUNCTION, n);
3318 break;
3319 case 1:
3320 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3321 break;
3322 case 2:
3323 ADDOP_I(c, CALL_FUNCTION_KW, n);
3324 break;
3325 case 3:
3326 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3327 break;
3328 }
3329 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330}
3331
Nick Coghlan650f0d02007-04-15 12:05:43 +00003332
3333/* List and set comprehensions and generator expressions work by creating a
3334 nested function to perform the actual iteration. This means that the
3335 iteration variables don't leak into the current scope.
3336 The defined function is called immediately following its definition, with the
3337 result of that call being the result of the expression.
3338 The LC/SC version returns the populated container, while the GE version is
3339 flagged in symtable.c as a generator, so it returns the generator object
3340 when the function is called.
3341 This code *knows* that the loop cannot contain break, continue, or return,
3342 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3343
3344 Possible cleanups:
3345 - iterate over the generator sequence instead of using recursion
3346*/
3347
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003348static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349compiler_comprehension_generator(struct compiler *c,
3350 asdl_seq *generators, int gen_index,
3351 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 /* generate code for the iterator, then each of the ifs,
3354 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 comprehension_ty gen;
3357 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003358 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 start = compiler_new_block(c);
3361 skip = compiler_new_block(c);
3362 if_cleanup = compiler_new_block(c);
3363 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3366 anchor == NULL)
3367 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 if (gen_index == 0) {
3372 /* Receive outermost iter as an implicit argument */
3373 c->u->u_argcount = 1;
3374 ADDOP_I(c, LOAD_FAST, 0);
3375 }
3376 else {
3377 /* Sub-iter - calculate on the fly */
3378 VISIT(c, expr, gen->iter);
3379 ADDOP(c, GET_ITER);
3380 }
3381 compiler_use_next_block(c, start);
3382 ADDOP_JREL(c, FOR_ITER, anchor);
3383 NEXT_BLOCK(c);
3384 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* XXX this needs to be cleaned up...a lot! */
3387 n = asdl_seq_LEN(gen->ifs);
3388 for (i = 0; i < n; i++) {
3389 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3390 VISIT(c, expr, e);
3391 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3392 NEXT_BLOCK(c);
3393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 if (++gen_index < asdl_seq_LEN(generators))
3396 if (!compiler_comprehension_generator(c,
3397 generators, gen_index,
3398 elt, val, type))
3399 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* only append after the last for generator */
3402 if (gen_index >= asdl_seq_LEN(generators)) {
3403 /* comprehension specific code */
3404 switch (type) {
3405 case COMP_GENEXP:
3406 VISIT(c, expr, elt);
3407 ADDOP(c, YIELD_VALUE);
3408 ADDOP(c, POP_TOP);
3409 break;
3410 case COMP_LISTCOMP:
3411 VISIT(c, expr, elt);
3412 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3413 break;
3414 case COMP_SETCOMP:
3415 VISIT(c, expr, elt);
3416 ADDOP_I(c, SET_ADD, gen_index + 1);
3417 break;
3418 case COMP_DICTCOMP:
3419 /* With 'd[k] = v', v is evaluated before k, so we do
3420 the same. */
3421 VISIT(c, expr, val);
3422 VISIT(c, expr, elt);
3423 ADDOP_I(c, MAP_ADD, gen_index + 1);
3424 break;
3425 default:
3426 return 0;
3427 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 compiler_use_next_block(c, skip);
3430 }
3431 compiler_use_next_block(c, if_cleanup);
3432 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3433 compiler_use_next_block(c, anchor);
3434
3435 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436}
3437
3438static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003439compiler_comprehension(struct compiler *c, expr_ty e, int type,
3440 identifier name, asdl_seq *generators, expr_ty elt,
3441 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 PyCodeObject *co = NULL;
3444 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003445 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 outermost_iter = ((comprehension_ty)
3448 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003449
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003450 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3451 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 if (type != COMP_GENEXP) {
3455 int op;
3456 switch (type) {
3457 case COMP_LISTCOMP:
3458 op = BUILD_LIST;
3459 break;
3460 case COMP_SETCOMP:
3461 op = BUILD_SET;
3462 break;
3463 case COMP_DICTCOMP:
3464 op = BUILD_MAP;
3465 break;
3466 default:
3467 PyErr_Format(PyExc_SystemError,
3468 "unknown comprehension type %d", type);
3469 goto error_in_scope;
3470 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 ADDOP_I(c, op, 0);
3473 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 if (!compiler_comprehension_generator(c, generators, 0, elt,
3476 val, type))
3477 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 if (type != COMP_GENEXP) {
3480 ADDOP(c, RETURN_VALUE);
3481 }
3482
3483 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003484 qualname = c->u->u_qualname;
3485 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003487 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 goto error;
3489
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003490 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003492 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 Py_DECREF(co);
3494
3495 VISIT(c, expr, outermost_iter);
3496 ADDOP(c, GET_ITER);
3497 ADDOP_I(c, CALL_FUNCTION, 1);
3498 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003499error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003501error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003502 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 Py_XDECREF(co);
3504 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003505}
3506
3507static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508compiler_genexp(struct compiler *c, expr_ty e)
3509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 static identifier name;
3511 if (!name) {
3512 name = PyUnicode_FromString("<genexpr>");
3513 if (!name)
3514 return 0;
3515 }
3516 assert(e->kind == GeneratorExp_kind);
3517 return compiler_comprehension(c, e, COMP_GENEXP, name,
3518 e->v.GeneratorExp.generators,
3519 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520}
3521
3522static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003523compiler_listcomp(struct compiler *c, expr_ty e)
3524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 static identifier name;
3526 if (!name) {
3527 name = PyUnicode_FromString("<listcomp>");
3528 if (!name)
3529 return 0;
3530 }
3531 assert(e->kind == ListComp_kind);
3532 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3533 e->v.ListComp.generators,
3534 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003535}
3536
3537static int
3538compiler_setcomp(struct compiler *c, expr_ty e)
3539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 static identifier name;
3541 if (!name) {
3542 name = PyUnicode_FromString("<setcomp>");
3543 if (!name)
3544 return 0;
3545 }
3546 assert(e->kind == SetComp_kind);
3547 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3548 e->v.SetComp.generators,
3549 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003550}
3551
3552
3553static int
3554compiler_dictcomp(struct compiler *c, expr_ty e)
3555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 static identifier name;
3557 if (!name) {
3558 name = PyUnicode_FromString("<dictcomp>");
3559 if (!name)
3560 return 0;
3561 }
3562 assert(e->kind == DictComp_kind);
3563 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3564 e->v.DictComp.generators,
3565 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003566}
3567
3568
3569static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570compiler_visit_keyword(struct compiler *c, keyword_ty k)
3571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3573 VISIT(c, expr, k->value);
3574 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575}
3576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 whether they are true or false.
3579
3580 Return values: 1 for true, 0 for false, -1 for non-constant.
3581 */
3582
3583static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003584expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 char *id;
3587 switch (e->kind) {
3588 case Ellipsis_kind:
3589 return 1;
3590 case Num_kind:
3591 return PyObject_IsTrue(e->v.Num.n);
3592 case Str_kind:
3593 return PyObject_IsTrue(e->v.Str.s);
3594 case Name_kind:
3595 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003596 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003597 if (id && strcmp(id, "__debug__") == 0)
3598 return !c->c_optimize;
3599 return -1;
3600 case NameConstant_kind: {
3601 PyObject *o = e->v.NameConstant.value;
3602 if (o == Py_None)
3603 return 0;
3604 else if (o == Py_True)
3605 return 1;
3606 else if (o == Py_False)
3607 return 0;
3608 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 default:
3610 return -1;
3611 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
Yury Selivanov75445082015-05-11 22:57:16 -04003614
3615/*
3616 Implements the async with statement.
3617
3618 The semantics outlined in that PEP are as follows:
3619
3620 async with EXPR as VAR:
3621 BLOCK
3622
3623 It is implemented roughly as:
3624
3625 context = EXPR
3626 exit = context.__aexit__ # not calling it
3627 value = await context.__aenter__()
3628 try:
3629 VAR = value # if VAR present in the syntax
3630 BLOCK
3631 finally:
3632 if an exception was raised:
3633 exc = copy of (exception, instance, traceback)
3634 else:
3635 exc = (None, None, None)
3636 if not (await exit(*exc)):
3637 raise
3638 */
3639static int
3640compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3641{
3642 basicblock *block, *finally;
3643 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3644
3645 assert(s->kind == AsyncWith_kind);
3646
3647 block = compiler_new_block(c);
3648 finally = compiler_new_block(c);
3649 if (!block || !finally)
3650 return 0;
3651
3652 /* Evaluate EXPR */
3653 VISIT(c, expr, item->context_expr);
3654
3655 ADDOP(c, BEFORE_ASYNC_WITH);
3656 ADDOP(c, GET_AWAITABLE);
3657 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3658 ADDOP(c, YIELD_FROM);
3659
3660 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3661
3662 /* SETUP_ASYNC_WITH pushes a finally block. */
3663 compiler_use_next_block(c, block);
3664 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3665 return 0;
3666 }
3667
3668 if (item->optional_vars) {
3669 VISIT(c, expr, item->optional_vars);
3670 }
3671 else {
3672 /* Discard result from context.__aenter__() */
3673 ADDOP(c, POP_TOP);
3674 }
3675
3676 pos++;
3677 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3678 /* BLOCK code */
3679 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3680 else if (!compiler_async_with(c, s, pos))
3681 return 0;
3682
3683 /* End of try block; start the finally block */
3684 ADDOP(c, POP_BLOCK);
3685 compiler_pop_fblock(c, FINALLY_TRY, block);
3686
3687 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3688 compiler_use_next_block(c, finally);
3689 if (!compiler_push_fblock(c, FINALLY_END, finally))
3690 return 0;
3691
3692 /* Finally block starts; context.__exit__ is on the stack under
3693 the exception or return information. Just issue our magic
3694 opcode. */
3695 ADDOP(c, WITH_CLEANUP_START);
3696
3697 ADDOP(c, GET_AWAITABLE);
3698 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3699 ADDOP(c, YIELD_FROM);
3700
3701 ADDOP(c, WITH_CLEANUP_FINISH);
3702
3703 /* Finally block ends. */
3704 ADDOP(c, END_FINALLY);
3705 compiler_pop_fblock(c, FINALLY_END, finally);
3706 return 1;
3707}
3708
3709
Guido van Rossumc2e20742006-02-27 22:32:47 +00003710/*
3711 Implements the with statement from PEP 343.
3712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003714
3715 with EXPR as VAR:
3716 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717
Guido van Rossumc2e20742006-02-27 22:32:47 +00003718 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719
Thomas Wouters477c8d52006-05-27 19:21:47 +00003720 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003721 exit = context.__exit__ # not calling it
3722 value = context.__enter__()
3723 try:
3724 VAR = value # if VAR present in the syntax
3725 BLOCK
3726 finally:
3727 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003729 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003731 exit(*exc)
3732 */
3733static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003734compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003735{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003736 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003737 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003738
3739 assert(s->kind == With_kind);
3740
Guido van Rossumc2e20742006-02-27 22:32:47 +00003741 block = compiler_new_block(c);
3742 finally = compiler_new_block(c);
3743 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003744 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003745
Thomas Wouters477c8d52006-05-27 19:21:47 +00003746 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003747 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003748 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003749
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003750 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003751 compiler_use_next_block(c, block);
3752 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003753 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003754 }
3755
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003756 if (item->optional_vars) {
3757 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003758 }
3759 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003761 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003762 }
3763
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003764 pos++;
3765 if (pos == asdl_seq_LEN(s->v.With.items))
3766 /* BLOCK code */
3767 VISIT_SEQ(c, stmt, s->v.With.body)
3768 else if (!compiler_with(c, s, pos))
3769 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003770
3771 /* End of try block; start the finally block */
3772 ADDOP(c, POP_BLOCK);
3773 compiler_pop_fblock(c, FINALLY_TRY, block);
3774
3775 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3776 compiler_use_next_block(c, finally);
3777 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003778 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003779
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003780 /* Finally block starts; context.__exit__ is on the stack under
3781 the exception or return information. Just issue our magic
3782 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003783 ADDOP(c, WITH_CLEANUP_START);
3784 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003785
3786 /* Finally block ends. */
3787 ADDOP(c, END_FINALLY);
3788 compiler_pop_fblock(c, FINALLY_END, finally);
3789 return 1;
3790}
3791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792static int
3793compiler_visit_expr(struct compiler *c, expr_ty e)
3794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 /* If expr e has a different line number than the last expr/stmt,
3796 set a new line number for the next instruction.
3797 */
3798 if (e->lineno > c->u->u_lineno) {
3799 c->u->u_lineno = e->lineno;
3800 c->u->u_lineno_set = 0;
3801 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003802 /* Updating the column offset is always harmless. */
3803 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 switch (e->kind) {
3805 case BoolOp_kind:
3806 return compiler_boolop(c, e);
3807 case BinOp_kind:
3808 VISIT(c, expr, e->v.BinOp.left);
3809 VISIT(c, expr, e->v.BinOp.right);
3810 ADDOP(c, binop(c, e->v.BinOp.op));
3811 break;
3812 case UnaryOp_kind:
3813 VISIT(c, expr, e->v.UnaryOp.operand);
3814 ADDOP(c, unaryop(e->v.UnaryOp.op));
3815 break;
3816 case Lambda_kind:
3817 return compiler_lambda(c, e);
3818 case IfExp_kind:
3819 return compiler_ifexp(c, e);
3820 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003823 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 case GeneratorExp_kind:
3825 return compiler_genexp(c, e);
3826 case ListComp_kind:
3827 return compiler_listcomp(c, e);
3828 case SetComp_kind:
3829 return compiler_setcomp(c, e);
3830 case DictComp_kind:
3831 return compiler_dictcomp(c, e);
3832 case Yield_kind:
3833 if (c->u->u_ste->ste_type != FunctionBlock)
3834 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003835 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3836 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003837 if (e->v.Yield.value) {
3838 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 }
3840 else {
3841 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3842 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003843 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003845 case YieldFrom_kind:
3846 if (c->u->u_ste->ste_type != FunctionBlock)
3847 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003848
3849 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3850 return compiler_error(c, "'yield from' inside async function");
3851
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003852 VISIT(c, expr, e->v.YieldFrom.value);
3853 ADDOP(c, GET_ITER);
3854 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3855 ADDOP(c, YIELD_FROM);
3856 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003857 case Await_kind:
3858 if (c->u->u_ste->ste_type != FunctionBlock)
3859 return compiler_error(c, "'await' outside function");
3860
3861 /* this check won't be triggered while we have AWAIT token */
3862 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3863 return compiler_error(c, "'await' outside async function");
3864
3865 VISIT(c, expr, e->v.Await.value);
3866 ADDOP(c, GET_AWAITABLE);
3867 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3868 ADDOP(c, YIELD_FROM);
3869 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 case Compare_kind:
3871 return compiler_compare(c, e);
3872 case Call_kind:
3873 return compiler_call(c, e);
3874 case Num_kind:
3875 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3876 break;
3877 case Str_kind:
3878 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3879 break;
3880 case Bytes_kind:
3881 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3882 break;
3883 case Ellipsis_kind:
3884 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3885 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003886 case NameConstant_kind:
3887 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3888 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 /* The following exprs can be assignment targets. */
3890 case Attribute_kind:
3891 if (e->v.Attribute.ctx != AugStore)
3892 VISIT(c, expr, e->v.Attribute.value);
3893 switch (e->v.Attribute.ctx) {
3894 case AugLoad:
3895 ADDOP(c, DUP_TOP);
3896 /* Fall through to load */
3897 case Load:
3898 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3899 break;
3900 case AugStore:
3901 ADDOP(c, ROT_TWO);
3902 /* Fall through to save */
3903 case Store:
3904 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3905 break;
3906 case Del:
3907 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3908 break;
3909 case Param:
3910 default:
3911 PyErr_SetString(PyExc_SystemError,
3912 "param invalid in attribute expression");
3913 return 0;
3914 }
3915 break;
3916 case Subscript_kind:
3917 switch (e->v.Subscript.ctx) {
3918 case AugLoad:
3919 VISIT(c, expr, e->v.Subscript.value);
3920 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3921 break;
3922 case Load:
3923 VISIT(c, expr, e->v.Subscript.value);
3924 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3925 break;
3926 case AugStore:
3927 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3928 break;
3929 case Store:
3930 VISIT(c, expr, e->v.Subscript.value);
3931 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3932 break;
3933 case Del:
3934 VISIT(c, expr, e->v.Subscript.value);
3935 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3936 break;
3937 case Param:
3938 default:
3939 PyErr_SetString(PyExc_SystemError,
3940 "param invalid in subscript expression");
3941 return 0;
3942 }
3943 break;
3944 case Starred_kind:
3945 switch (e->v.Starred.ctx) {
3946 case Store:
3947 /* In all legitimate cases, the Starred node was already replaced
3948 * by compiler_list/compiler_tuple. XXX: is that okay? */
3949 return compiler_error(c,
3950 "starred assignment target must be in a list or tuple");
3951 default:
3952 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003953 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 }
3955 break;
3956 case Name_kind:
3957 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3958 /* child nodes of List and Tuple will have expr_context set */
3959 case List_kind:
3960 return compiler_list(c, e);
3961 case Tuple_kind:
3962 return compiler_tuple(c, e);
3963 }
3964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965}
3966
3967static int
3968compiler_augassign(struct compiler *c, stmt_ty s)
3969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 expr_ty e = s->v.AugAssign.target;
3971 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 switch (e->kind) {
3976 case Attribute_kind:
3977 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3978 AugLoad, e->lineno, e->col_offset, c->c_arena);
3979 if (auge == NULL)
3980 return 0;
3981 VISIT(c, expr, auge);
3982 VISIT(c, expr, s->v.AugAssign.value);
3983 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3984 auge->v.Attribute.ctx = AugStore;
3985 VISIT(c, expr, auge);
3986 break;
3987 case Subscript_kind:
3988 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3989 AugLoad, e->lineno, e->col_offset, c->c_arena);
3990 if (auge == NULL)
3991 return 0;
3992 VISIT(c, expr, auge);
3993 VISIT(c, expr, s->v.AugAssign.value);
3994 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3995 auge->v.Subscript.ctx = AugStore;
3996 VISIT(c, expr, auge);
3997 break;
3998 case Name_kind:
3999 if (!compiler_nameop(c, e->v.Name.id, Load))
4000 return 0;
4001 VISIT(c, expr, s->v.AugAssign.value);
4002 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4003 return compiler_nameop(c, e->v.Name.id, Store);
4004 default:
4005 PyErr_Format(PyExc_SystemError,
4006 "invalid node type (%d) for augmented assignment",
4007 e->kind);
4008 return 0;
4009 }
4010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004011}
4012
4013static int
4014compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 struct fblockinfo *f;
4017 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4018 PyErr_SetString(PyExc_SystemError,
4019 "too many statically nested blocks");
4020 return 0;
4021 }
4022 f = &c->u->u_fblock[c->u->u_nfblocks++];
4023 f->fb_type = t;
4024 f->fb_block = b;
4025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004026}
4027
4028static void
4029compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 struct compiler_unit *u = c->u;
4032 assert(u->u_nfblocks > 0);
4033 u->u_nfblocks--;
4034 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4035 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004036}
4037
Thomas Wouters89f507f2006-12-13 04:49:30 +00004038static int
4039compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 int i;
4041 struct compiler_unit *u = c->u;
4042 for (i = 0; i < u->u_nfblocks; ++i) {
4043 if (u->u_fblock[i].fb_type == LOOP)
4044 return 1;
4045 }
4046 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004047}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048/* Raises a SyntaxError and returns 0.
4049 If something goes wrong, a different exception may be raised.
4050*/
4051
4052static int
4053compiler_error(struct compiler *c, const char *errstr)
4054{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004055 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057
Victor Stinner14e461d2013-08-26 22:28:21 +02004058 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (!loc) {
4060 Py_INCREF(Py_None);
4061 loc = Py_None;
4062 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004063 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004064 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 if (!u)
4066 goto exit;
4067 v = Py_BuildValue("(zO)", errstr, u);
4068 if (!v)
4069 goto exit;
4070 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 Py_DECREF(loc);
4073 Py_XDECREF(u);
4074 Py_XDECREF(v);
4075 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076}
4077
4078static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079compiler_handle_subscr(struct compiler *c, const char *kind,
4080 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 /* XXX this code is duplicated */
4085 switch (ctx) {
4086 case AugLoad: /* fall through to Load */
4087 case Load: op = BINARY_SUBSCR; break;
4088 case AugStore:/* fall through to Store */
4089 case Store: op = STORE_SUBSCR; break;
4090 case Del: op = DELETE_SUBSCR; break;
4091 case Param:
4092 PyErr_Format(PyExc_SystemError,
4093 "invalid %s kind %d in subscript\n",
4094 kind, ctx);
4095 return 0;
4096 }
4097 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004098 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 }
4100 else if (ctx == AugStore) {
4101 ADDOP(c, ROT_THREE);
4102 }
4103 ADDOP(c, op);
4104 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105}
4106
4107static int
4108compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 int n = 2;
4111 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 /* only handles the cases where BUILD_SLICE is emitted */
4114 if (s->v.Slice.lower) {
4115 VISIT(c, expr, s->v.Slice.lower);
4116 }
4117 else {
4118 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4119 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 if (s->v.Slice.upper) {
4122 VISIT(c, expr, s->v.Slice.upper);
4123 }
4124 else {
4125 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4126 }
4127
4128 if (s->v.Slice.step) {
4129 n++;
4130 VISIT(c, expr, s->v.Slice.step);
4131 }
4132 ADDOP_I(c, BUILD_SLICE, n);
4133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134}
4135
4136static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4138 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 switch (s->kind) {
4141 case Slice_kind:
4142 return compiler_slice(c, s, ctx);
4143 case Index_kind:
4144 VISIT(c, expr, s->v.Index.value);
4145 break;
4146 case ExtSlice_kind:
4147 default:
4148 PyErr_SetString(PyExc_SystemError,
4149 "extended slice invalid in nested slice");
4150 return 0;
4151 }
4152 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153}
4154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004155static int
4156compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 char * kindname = NULL;
4159 switch (s->kind) {
4160 case Index_kind:
4161 kindname = "index";
4162 if (ctx != AugStore) {
4163 VISIT(c, expr, s->v.Index.value);
4164 }
4165 break;
4166 case Slice_kind:
4167 kindname = "slice";
4168 if (ctx != AugStore) {
4169 if (!compiler_slice(c, s, ctx))
4170 return 0;
4171 }
4172 break;
4173 case ExtSlice_kind:
4174 kindname = "extended slice";
4175 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004176 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 for (i = 0; i < n; i++) {
4178 slice_ty sub = (slice_ty)asdl_seq_GET(
4179 s->v.ExtSlice.dims, i);
4180 if (!compiler_visit_nested_slice(c, sub, ctx))
4181 return 0;
4182 }
4183 ADDOP_I(c, BUILD_TUPLE, n);
4184 }
4185 break;
4186 default:
4187 PyErr_Format(PyExc_SystemError,
4188 "invalid subscript kind %d", s->kind);
4189 return 0;
4190 }
4191 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192}
4193
Thomas Wouters89f507f2006-12-13 04:49:30 +00004194/* End of the compiler section, beginning of the assembler section */
4195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196/* do depth-first search of basic block graph, starting with block.
4197 post records the block indices in post-order.
4198
4199 XXX must handle implicit jumps from one block to next
4200*/
4201
Thomas Wouters89f507f2006-12-13 04:49:30 +00004202struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 PyObject *a_bytecode; /* string containing bytecode */
4204 int a_offset; /* offset into bytecode */
4205 int a_nblocks; /* number of reachable blocks */
4206 basicblock **a_postorder; /* list of blocks in dfs postorder */
4207 PyObject *a_lnotab; /* string containing lnotab */
4208 int a_lnotab_off; /* offset into lnotab */
4209 int a_lineno; /* last lineno of emitted instruction */
4210 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004211};
4212
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213static void
4214dfs(struct compiler *c, basicblock *b, struct assembler *a)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 int i;
4217 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 if (b->b_seen)
4220 return;
4221 b->b_seen = 1;
4222 if (b->b_next != NULL)
4223 dfs(c, b->b_next, a);
4224 for (i = 0; i < b->b_iused; i++) {
4225 instr = &b->b_instr[i];
4226 if (instr->i_jrel || instr->i_jabs)
4227 dfs(c, instr->i_target, a);
4228 }
4229 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230}
4231
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004232static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4234{
Larry Hastings3a907972013-11-23 14:49:22 -08004235 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 struct instr *instr;
4237 if (b->b_seen || b->b_startdepth >= depth)
4238 return maxdepth;
4239 b->b_seen = 1;
4240 b->b_startdepth = depth;
4241 for (i = 0; i < b->b_iused; i++) {
4242 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004243 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4244 if (effect == PY_INVALID_STACK_EFFECT) {
4245 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4246 Py_FatalError("PyCompile_OpcodeStackEffect()");
4247 }
4248 depth += effect;
4249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 if (depth > maxdepth)
4251 maxdepth = depth;
4252 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4253 if (instr->i_jrel || instr->i_jabs) {
4254 target_depth = depth;
4255 if (instr->i_opcode == FOR_ITER) {
4256 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004257 }
4258 else if (instr->i_opcode == SETUP_FINALLY ||
4259 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 target_depth = depth+3;
4261 if (target_depth > maxdepth)
4262 maxdepth = target_depth;
4263 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004264 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4265 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4266 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 maxdepth = stackdepth_walk(c, instr->i_target,
4268 target_depth, maxdepth);
4269 if (instr->i_opcode == JUMP_ABSOLUTE ||
4270 instr->i_opcode == JUMP_FORWARD) {
4271 goto out; /* remaining code is dead */
4272 }
4273 }
4274 }
4275 if (b->b_next)
4276 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 b->b_seen = 0;
4279 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280}
4281
4282/* Find the flow path that needs the largest stack. We assume that
4283 * cycles in the flow graph have no net effect on the stack depth.
4284 */
4285static int
4286stackdepth(struct compiler *c)
4287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 basicblock *b, *entryblock;
4289 entryblock = NULL;
4290 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4291 b->b_seen = 0;
4292 b->b_startdepth = INT_MIN;
4293 entryblock = b;
4294 }
4295 if (!entryblock)
4296 return 0;
4297 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004298}
4299
4300static int
4301assemble_init(struct assembler *a, int nblocks, int firstlineno)
4302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 memset(a, 0, sizeof(struct assembler));
4304 a->a_lineno = firstlineno;
4305 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4306 if (!a->a_bytecode)
4307 return 0;
4308 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4309 if (!a->a_lnotab)
4310 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004311 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 PyErr_NoMemory();
4313 return 0;
4314 }
4315 a->a_postorder = (basicblock **)PyObject_Malloc(
4316 sizeof(basicblock *) * nblocks);
4317 if (!a->a_postorder) {
4318 PyErr_NoMemory();
4319 return 0;
4320 }
4321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322}
4323
4324static void
4325assemble_free(struct assembler *a)
4326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 Py_XDECREF(a->a_bytecode);
4328 Py_XDECREF(a->a_lnotab);
4329 if (a->a_postorder)
4330 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331}
4332
4333/* Return the size of a basic block in bytes. */
4334
4335static int
4336instrsize(struct instr *instr)
4337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 if (!instr->i_hasarg)
4339 return 1; /* 1 byte for the opcode*/
4340 if (instr->i_oparg > 0xffff)
4341 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4342 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343}
4344
4345static int
4346blocksize(basicblock *b)
4347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 int i;
4349 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 for (i = 0; i < b->b_iused; i++)
4352 size += instrsize(&b->b_instr[i]);
4353 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354}
4355
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004356/* Appends a pair to the end of the line number table, a_lnotab, representing
4357 the instruction's bytecode offset and line number. See
4358 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004359
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004360static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004364 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 d_bytecode = a->a_offset - a->a_lineno_off;
4368 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 assert(d_bytecode >= 0);
4371 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 if(d_bytecode == 0 && d_lineno == 0)
4374 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (d_bytecode > 255) {
4377 int j, nbytes, ncodes = d_bytecode / 255;
4378 nbytes = a->a_lnotab_off + 2 * ncodes;
4379 len = PyBytes_GET_SIZE(a->a_lnotab);
4380 if (nbytes >= len) {
4381 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4382 len = nbytes;
4383 else if (len <= INT_MAX / 2)
4384 len *= 2;
4385 else {
4386 PyErr_NoMemory();
4387 return 0;
4388 }
4389 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4390 return 0;
4391 }
4392 lnotab = (unsigned char *)
4393 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4394 for (j = 0; j < ncodes; j++) {
4395 *lnotab++ = 255;
4396 *lnotab++ = 0;
4397 }
4398 d_bytecode -= ncodes * 255;
4399 a->a_lnotab_off += ncodes * 2;
4400 }
4401 assert(d_bytecode <= 255);
4402 if (d_lineno > 255) {
4403 int j, nbytes, ncodes = d_lineno / 255;
4404 nbytes = a->a_lnotab_off + 2 * ncodes;
4405 len = PyBytes_GET_SIZE(a->a_lnotab);
4406 if (nbytes >= len) {
4407 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4408 len = nbytes;
4409 else if (len <= INT_MAX / 2)
4410 len *= 2;
4411 else {
4412 PyErr_NoMemory();
4413 return 0;
4414 }
4415 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4416 return 0;
4417 }
4418 lnotab = (unsigned char *)
4419 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4420 *lnotab++ = d_bytecode;
4421 *lnotab++ = 255;
4422 d_bytecode = 0;
4423 for (j = 1; j < ncodes; j++) {
4424 *lnotab++ = 0;
4425 *lnotab++ = 255;
4426 }
4427 d_lineno -= ncodes * 255;
4428 a->a_lnotab_off += ncodes * 2;
4429 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 len = PyBytes_GET_SIZE(a->a_lnotab);
4432 if (a->a_lnotab_off + 2 >= len) {
4433 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4434 return 0;
4435 }
4436 lnotab = (unsigned char *)
4437 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 a->a_lnotab_off += 2;
4440 if (d_bytecode) {
4441 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004442 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 }
4444 else { /* First line of a block; def stmt, etc. */
4445 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004446 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 }
4448 a->a_lineno = i->i_lineno;
4449 a->a_lineno_off = a->a_offset;
4450 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004451}
4452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004453/* assemble_emit()
4454 Extend the bytecode with a new instruction.
4455 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004456*/
4457
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004458static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004459assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 int size, arg = 0, ext = 0;
4462 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4463 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 size = instrsize(i);
4466 if (i->i_hasarg) {
4467 arg = i->i_oparg;
4468 ext = arg >> 16;
4469 }
4470 if (i->i_lineno && !assemble_lnotab(a, i))
4471 return 0;
4472 if (a->a_offset + size >= len) {
4473 if (len > PY_SSIZE_T_MAX / 2)
4474 return 0;
4475 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4476 return 0;
4477 }
4478 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4479 a->a_offset += size;
4480 if (size == 6) {
4481 assert(i->i_hasarg);
4482 *code++ = (char)EXTENDED_ARG;
4483 *code++ = ext & 0xff;
4484 *code++ = ext >> 8;
4485 arg &= 0xffff;
4486 }
4487 *code++ = i->i_opcode;
4488 if (i->i_hasarg) {
4489 assert(size == 3 || size == 6);
4490 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004491 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 }
4493 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004494}
4495
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004496static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004497assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 basicblock *b;
4500 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4501 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 /* Compute the size of each block and fixup jump args.
4504 Replace block pointer with position in bytecode. */
4505 do {
4506 totsize = 0;
4507 for (i = a->a_nblocks - 1; i >= 0; i--) {
4508 b = a->a_postorder[i];
4509 bsize = blocksize(b);
4510 b->b_offset = totsize;
4511 totsize += bsize;
4512 }
4513 last_extended_arg_count = extended_arg_count;
4514 extended_arg_count = 0;
4515 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4516 bsize = b->b_offset;
4517 for (i = 0; i < b->b_iused; i++) {
4518 struct instr *instr = &b->b_instr[i];
4519 /* Relative jumps are computed relative to
4520 the instruction pointer after fetching
4521 the jump instruction.
4522 */
4523 bsize += instrsize(instr);
4524 if (instr->i_jabs)
4525 instr->i_oparg = instr->i_target->b_offset;
4526 else if (instr->i_jrel) {
4527 int delta = instr->i_target->b_offset - bsize;
4528 instr->i_oparg = delta;
4529 }
4530 else
4531 continue;
4532 if (instr->i_oparg > 0xffff)
4533 extended_arg_count++;
4534 }
4535 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 /* XXX: This is an awful hack that could hurt performance, but
4538 on the bright side it should work until we come up
4539 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 The issue is that in the first loop blocksize() is called
4542 which calls instrsize() which requires i_oparg be set
4543 appropriately. There is a bootstrap problem because
4544 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 So we loop until we stop seeing new EXTENDED_ARGs.
4547 The only EXTENDED_ARGs that could be popping up are
4548 ones in jump instructions. So this should converge
4549 fairly quickly.
4550 */
4551 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004552}
4553
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004554static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004555dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 PyObject *tuple, *k, *v;
4558 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 tuple = PyTuple_New(size);
4561 if (tuple == NULL)
4562 return NULL;
4563 while (PyDict_Next(dict, &pos, &k, &v)) {
4564 i = PyLong_AS_LONG(v);
4565 /* The keys of the dictionary are tuples. (see compiler_add_o)
4566 The object we want is always first, though. */
4567 k = PyTuple_GET_ITEM(k, 0);
4568 Py_INCREF(k);
4569 assert((i - offset) < size);
4570 assert((i - offset) >= 0);
4571 PyTuple_SET_ITEM(tuple, i - offset, k);
4572 }
4573 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004574}
4575
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004576static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004577compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004580 int flags = 0;
4581 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004583 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (ste->ste_nested)
4585 flags |= CO_NESTED;
4586 if (ste->ste_generator)
4587 flags |= CO_GENERATOR;
4588 if (ste->ste_varargs)
4589 flags |= CO_VARARGS;
4590 if (ste->ste_varkeywords)
4591 flags |= CO_VARKEYWORDS;
4592 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 /* (Only) inherit compilerflags in PyCF_MASK */
4595 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 n = PyDict_Size(c->u->u_freevars);
4598 if (n < 0)
4599 return -1;
4600 if (n == 0) {
4601 n = PyDict_Size(c->u->u_cellvars);
4602 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004603 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004605 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 }
4607 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004610}
4611
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004612static PyCodeObject *
4613makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 PyObject *tmp;
4616 PyCodeObject *co = NULL;
4617 PyObject *consts = NULL;
4618 PyObject *names = NULL;
4619 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 PyObject *name = NULL;
4621 PyObject *freevars = NULL;
4622 PyObject *cellvars = NULL;
4623 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004624 Py_ssize_t nlocals;
4625 int nlocals_int;
4626 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004627 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 tmp = dict_keys_inorder(c->u->u_consts, 0);
4630 if (!tmp)
4631 goto error;
4632 consts = PySequence_List(tmp); /* optimize_code requires a list */
4633 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 names = dict_keys_inorder(c->u->u_names, 0);
4636 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4637 if (!consts || !names || !varnames)
4638 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4641 if (!cellvars)
4642 goto error;
4643 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4644 if (!freevars)
4645 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004648 assert(nlocals < INT_MAX);
4649 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 flags = compute_code_flags(c);
4652 if (flags < 0)
4653 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4656 if (!bytecode)
4657 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4660 if (!tmp)
4661 goto error;
4662 Py_DECREF(consts);
4663 consts = tmp;
4664
Victor Stinnerf8e32212013-11-19 23:56:34 +01004665 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4666 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4667 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004668 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 bytecode, consts, names, varnames,
4670 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004671 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 c->u->u_firstlineno,
4673 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004674 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 Py_XDECREF(consts);
4676 Py_XDECREF(names);
4677 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 Py_XDECREF(name);
4679 Py_XDECREF(freevars);
4680 Py_XDECREF(cellvars);
4681 Py_XDECREF(bytecode);
4682 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004683}
4684
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004685
4686/* For debugging purposes only */
4687#if 0
4688static void
4689dump_instr(const struct instr *i)
4690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 const char *jrel = i->i_jrel ? "jrel " : "";
4692 const char *jabs = i->i_jabs ? "jabs " : "";
4693 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 *arg = '\0';
4696 if (i->i_hasarg)
4697 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4700 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004701}
4702
4703static void
4704dump_basicblock(const basicblock *b)
4705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 const char *seen = b->b_seen ? "seen " : "";
4707 const char *b_return = b->b_return ? "return " : "";
4708 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4709 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4710 if (b->b_instr) {
4711 int i;
4712 for (i = 0; i < b->b_iused; i++) {
4713 fprintf(stderr, " [%02d] ", i);
4714 dump_instr(b->b_instr + i);
4715 }
4716 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004717}
4718#endif
4719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004720static PyCodeObject *
4721assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 basicblock *b, *entryblock;
4724 struct assembler a;
4725 int i, j, nblocks;
4726 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 /* Make sure every block that falls off the end returns None.
4729 XXX NEXT_BLOCK() isn't quite right, because if the last
4730 block ends with a jump or return b_next shouldn't set.
4731 */
4732 if (!c->u->u_curblock->b_return) {
4733 NEXT_BLOCK(c);
4734 if (addNone)
4735 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4736 ADDOP(c, RETURN_VALUE);
4737 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 nblocks = 0;
4740 entryblock = NULL;
4741 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4742 nblocks++;
4743 entryblock = b;
4744 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 /* Set firstlineno if it wasn't explicitly set. */
4747 if (!c->u->u_firstlineno) {
4748 if (entryblock && entryblock->b_instr)
4749 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4750 else
4751 c->u->u_firstlineno = 1;
4752 }
4753 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4754 goto error;
4755 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 /* Can't modify the bytecode after computing jump offsets. */
4758 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 /* Emit code in reverse postorder from dfs. */
4761 for (i = a.a_nblocks - 1; i >= 0; i--) {
4762 b = a.a_postorder[i];
4763 for (j = 0; j < b->b_iused; j++)
4764 if (!assemble_emit(&a, &b->b_instr[j]))
4765 goto error;
4766 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4769 goto error;
4770 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4771 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 assemble_free(&a);
4776 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004777}
Georg Brandl8334fd92010-12-04 10:26:46 +00004778
4779#undef PyAST_Compile
4780PyAPI_FUNC(PyCodeObject *)
4781PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4782 PyArena *arena)
4783{
4784 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4785}
4786