blob: 7631f4e55a8755c55e6851d19bca4fd897ffb0dd [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) {
Martin Panter7462b6492015-11-02 03:37:02 +0000551 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500552 _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:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700988 return 1 - 2*oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 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;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001067 case GET_YIELD_FROM_ITER:
1068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001070 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
Larry Hastings3a907972013-11-23 14:49:22 -08001072 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075/* Add an opcode with no argument.
1076 Returns 0 on failure, 1 on success.
1077*/
1078
1079static int
1080compiler_addop(struct compiler *c, int opcode)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 basicblock *b;
1083 struct instr *i;
1084 int off;
1085 off = compiler_next_instr(c, c->u->u_curblock);
1086 if (off < 0)
1087 return 0;
1088 b = c->u->u_curblock;
1089 i = &b->b_instr[off];
1090 i->i_opcode = opcode;
1091 i->i_hasarg = 0;
1092 if (opcode == RETURN_VALUE)
1093 b->b_return = 1;
1094 compiler_set_lineno(c, off);
1095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096}
1097
Victor Stinnerf8e32212013-11-19 23:56:34 +01001098static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *t, *v;
1102 Py_ssize_t arg;
1103 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104
Serhiy Storchaka95949422013-08-27 19:40:23 +03001105 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1107 if (PyFloat_Check(o)) {
1108 d = PyFloat_AS_DOUBLE(o);
1109 /* all we need is to make the tuple different in either the 0.0
1110 * or -0.0 case from all others, just to avoid the "coercion".
1111 */
1112 if (d == 0.0 && copysign(1.0, d) < 0.0)
1113 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1114 else
1115 t = PyTuple_Pack(2, o, o->ob_type);
1116 }
1117 else if (PyComplex_Check(o)) {
1118 Py_complex z;
1119 int real_negzero, imag_negzero;
1120 /* For the complex case we must make complex(x, 0.)
1121 different from complex(x, -0.) and complex(0., y)
1122 different from complex(-0., y), for any x and y.
1123 All four complex zeros must be distinguished.*/
1124 z = PyComplex_AsCComplex(o);
1125 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1126 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1127 if (real_negzero && imag_negzero) {
1128 t = PyTuple_Pack(5, o, o->ob_type,
1129 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 else if (imag_negzero) {
1132 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 else if (real_negzero) {
1135 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1136 }
1137 else {
1138 t = PyTuple_Pack(2, o, o->ob_type);
1139 }
1140 }
1141 else {
1142 t = PyTuple_Pack(2, o, o->ob_type);
1143 }
1144 if (t == NULL)
1145 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 v = PyDict_GetItem(dict, t);
1148 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001149 if (PyErr_Occurred()) {
1150 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001154 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (!v) {
1156 Py_DECREF(t);
1157 return -1;
1158 }
1159 if (PyDict_SetItem(dict, t, v) < 0) {
1160 Py_DECREF(t);
1161 Py_DECREF(v);
1162 return -1;
1163 }
1164 Py_DECREF(v);
1165 }
1166 else
1167 arg = PyLong_AsLong(v);
1168 Py_DECREF(t);
1169 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170}
1171
1172static int
1173compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001176 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001178 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179 return compiler_addop_i(c, opcode, arg);
1180}
1181
1182static int
1183compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001186 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1188 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001189 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190 arg = compiler_add_o(c, dict, mangled);
1191 Py_DECREF(mangled);
1192 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001193 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 return compiler_addop_i(c, opcode, arg);
1195}
1196
1197/* Add an opcode with an integer argument.
1198 Returns 0 on failure, 1 on success.
1199*/
1200
1201static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001202compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 struct instr *i;
1205 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001206
1207 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1208 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001209 assert((-2147483647-1) <= oparg);
1210 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 off = compiler_next_instr(c, c->u->u_curblock);
1213 if (off < 0)
1214 return 0;
1215 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001216 i->i_opcode = opcode;
1217 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 i->i_hasarg = 1;
1219 compiler_set_lineno(c, off);
1220 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221}
1222
1223static int
1224compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 struct instr *i;
1227 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 assert(b != NULL);
1230 off = compiler_next_instr(c, c->u->u_curblock);
1231 if (off < 0)
1232 return 0;
1233 i = &c->u->u_curblock->b_instr[off];
1234 i->i_opcode = opcode;
1235 i->i_target = b;
1236 i->i_hasarg = 1;
1237 if (absolute)
1238 i->i_jabs = 1;
1239 else
1240 i->i_jrel = 1;
1241 compiler_set_lineno(c, off);
1242 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243}
1244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1246 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 it as the current block. NEXT_BLOCK() also creates an implicit jump
1248 from the current block to the new block.
1249*/
1250
Thomas Wouters89f507f2006-12-13 04:49:30 +00001251/* The returns inside these macros make it impossible to decref objects
1252 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253*/
1254
1255
1256#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (compiler_use_new_block((C)) == NULL) \
1258 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259}
1260
1261#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (compiler_next_block((C)) == NULL) \
1263 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (!compiler_addop((C), (OP))) \
1268 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269}
1270
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001271#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!compiler_addop((C), (OP))) { \
1273 compiler_exit_scope(c); \
1274 return 0; \
1275 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001276}
1277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
1283#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1285 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286}
1287
1288#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!compiler_addop_i((C), (OP), (O))) \
1290 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291}
1292
1293#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_addop_j((C), (OP), (O), 1)) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (!compiler_addop_j((C), (OP), (O), 0)) \
1300 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301}
1302
1303/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1304 the ASDL name to synthesize the name of the C type and the visit function.
1305*/
1306
1307#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (!compiler_visit_ ## TYPE((C), (V))) \
1309 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001312#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!compiler_visit_ ## TYPE((C), (V))) { \
1314 compiler_exit_scope(c); \
1315 return 0; \
1316 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001317}
1318
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!compiler_visit_slice((C), (V), (CTX))) \
1321 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 int _i; \
1326 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1327 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1328 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1329 if (!compiler_visit_ ## TYPE((C), elt)) \
1330 return 0; \
1331 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332}
1333
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001334#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 int _i; \
1336 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1337 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1338 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1339 if (!compiler_visit_ ## TYPE((C), elt)) { \
1340 compiler_exit_scope(c); \
1341 return 0; \
1342 } \
1343 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001344}
1345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346static int
1347compiler_isdocstring(stmt_ty s)
1348{
1349 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351 return s->v.Expr.value->kind == Str_kind;
1352}
1353
1354/* Compile a sequence of statements, checking for a docstring. */
1355
1356static int
1357compiler_body(struct compiler *c, asdl_seq *stmts)
1358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 int i = 0;
1360 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (!asdl_seq_LEN(stmts))
1363 return 1;
1364 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001365 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* don't generate docstrings if -OO */
1367 i = 1;
1368 VISIT(c, expr, st->v.Expr.value);
1369 if (!compiler_nameop(c, __doc__, Store))
1370 return 0;
1371 }
1372 for (; i < asdl_seq_LEN(stmts); i++)
1373 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1374 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375}
1376
1377static PyCodeObject *
1378compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 PyCodeObject *co;
1381 int addNone = 1;
1382 static PyObject *module;
1383 if (!module) {
1384 module = PyUnicode_InternFromString("<module>");
1385 if (!module)
1386 return NULL;
1387 }
1388 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001389 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 return NULL;
1391 switch (mod->kind) {
1392 case Module_kind:
1393 if (!compiler_body(c, mod->v.Module.body)) {
1394 compiler_exit_scope(c);
1395 return 0;
1396 }
1397 break;
1398 case Interactive_kind:
1399 c->c_interactive = 1;
1400 VISIT_SEQ_IN_SCOPE(c, stmt,
1401 mod->v.Interactive.body);
1402 break;
1403 case Expression_kind:
1404 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1405 addNone = 0;
1406 break;
1407 case Suite_kind:
1408 PyErr_SetString(PyExc_SystemError,
1409 "suite should not be possible");
1410 return 0;
1411 default:
1412 PyErr_Format(PyExc_SystemError,
1413 "module kind %d should not be possible",
1414 mod->kind);
1415 return 0;
1416 }
1417 co = assemble(c, addNone);
1418 compiler_exit_scope(c);
1419 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001420}
1421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422/* The test for LOCAL must come before the test for FREE in order to
1423 handle classes where name is both local and free. The local var is
1424 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001425*/
1426
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427static int
1428get_ref_type(struct compiler *c, PyObject *name)
1429{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001430 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001431 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1432 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1433 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001434 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (scope == 0) {
1436 char buf[350];
1437 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001438 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001440 PyUnicode_AsUTF8(name),
1441 PyUnicode_AsUTF8(c->u->u_name),
1442 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1443 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1444 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1445 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 );
1447 Py_FatalError(buf);
1448 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451}
1452
1453static int
1454compiler_lookup_arg(PyObject *dict, PyObject *name)
1455{
1456 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001457 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001459 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001461 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001463 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001464 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465}
1466
1467static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001468compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001470 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001471 if (qualname == NULL)
1472 qualname = co->co_name;
1473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (free == 0) {
1475 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001476 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 ADDOP_I(c, MAKE_FUNCTION, args);
1478 return 1;
1479 }
1480 for (i = 0; i < free; ++i) {
1481 /* Bypass com_addop_varname because it will generate
1482 LOAD_DEREF but LOAD_CLOSURE is needed.
1483 */
1484 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1485 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 /* Special case: If a class contains a method with a
1488 free variable that has the same name as a method,
1489 the name will be considered free *and* local in the
1490 class. It should be handled by the closure, as
1491 well as by the normal name loookup logic.
1492 */
1493 reftype = get_ref_type(c, name);
1494 if (reftype == CELL)
1495 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1496 else /* (reftype == FREE) */
1497 arg = compiler_lookup_arg(c->u->u_freevars, name);
1498 if (arg == -1) {
1499 fprintf(stderr,
1500 "lookup %s in %s %d %d\n"
1501 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001502 PyUnicode_AsUTF8(PyObject_Repr(name)),
1503 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001505 PyUnicode_AsUTF8(co->co_name),
1506 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 Py_FatalError("compiler_make_closure()");
1508 }
1509 ADDOP_I(c, LOAD_CLOSURE, arg);
1510 }
1511 ADDOP_I(c, BUILD_TUPLE, free);
1512 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001513 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 ADDOP_I(c, MAKE_CLOSURE, args);
1515 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516}
1517
1518static int
1519compiler_decorators(struct compiler *c, asdl_seq* decos)
1520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!decos)
1524 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1527 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1528 }
1529 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530}
1531
1532static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001533compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 int i, default_count = 0;
1537 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1538 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1539 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1540 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001541 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1542 if (!mangled)
1543 return -1;
1544 ADDOP_O(c, LOAD_CONST, mangled, consts);
1545 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (!compiler_visit_expr(c, default_)) {
1547 return -1;
1548 }
1549 default_count++;
1550 }
1551 }
1552 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001553}
1554
1555static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001556compiler_visit_argannotation(struct compiler *c, identifier id,
1557 expr_ty annotation, PyObject *names)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001560 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001562 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001563 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001564 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001565 if (PyList_Append(names, mangled) < 0) {
1566 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001567 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001568 }
1569 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001571 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001572}
1573
1574static int
1575compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1576 PyObject *names)
1577{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001578 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 for (i = 0; i < asdl_seq_LEN(args); i++) {
1580 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001581 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 c,
1583 arg->arg,
1584 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001585 names))
1586 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001588 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001589}
1590
1591static int
1592compiler_visit_annotations(struct compiler *c, arguments_ty args,
1593 expr_ty returns)
1594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 /* Push arg annotations and a list of the argument names. Return the #
1596 of items pushed. The expressions are evaluated out-of-order wrt the
1597 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1600 */
1601 static identifier return_str;
1602 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001603 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 names = PyList_New(0);
1605 if (!names)
1606 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001607
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001608 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001610 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001611 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001612 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001614 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001616 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001617 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001618 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (!return_str) {
1622 return_str = PyUnicode_InternFromString("return");
1623 if (!return_str)
1624 goto error;
1625 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001626 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 goto error;
1628 }
1629
1630 len = PyList_GET_SIZE(names);
1631 if (len > 65534) {
1632 /* len must fit in 16 bits, and len is incremented below */
1633 PyErr_SetString(PyExc_SyntaxError,
1634 "too many annotations");
1635 goto error;
1636 }
1637 if (len) {
1638 /* convert names to a tuple and place on stack */
1639 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001640 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 PyObject *s = PyTuple_New(len);
1642 if (!s)
1643 goto error;
1644 for (i = 0; i < len; i++) {
1645 elt = PyList_GET_ITEM(names, i);
1646 Py_INCREF(elt);
1647 PyTuple_SET_ITEM(s, i, elt);
1648 }
1649 ADDOP_O(c, LOAD_CONST, s, consts);
1650 Py_DECREF(s);
1651 len++; /* include the just-pushed tuple */
1652 }
1653 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001654
1655 /* We just checked that len <= 65535, see above */
1656 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001657
1658error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 Py_DECREF(names);
1660 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001661}
1662
1663static int
Yury Selivanov75445082015-05-11 22:57:16 -04001664compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001667 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001668 arguments_ty args;
1669 expr_ty returns;
1670 identifier name;
1671 asdl_seq* decos;
1672 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001674 Py_ssize_t i, n, arglength;
1675 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001677 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678
Yury Selivanov75445082015-05-11 22:57:16 -04001679
1680 if (is_async) {
1681 assert(s->kind == AsyncFunctionDef_kind);
1682
1683 args = s->v.AsyncFunctionDef.args;
1684 returns = s->v.AsyncFunctionDef.returns;
1685 decos = s->v.AsyncFunctionDef.decorator_list;
1686 name = s->v.AsyncFunctionDef.name;
1687 body = s->v.AsyncFunctionDef.body;
1688
1689 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1690 } else {
1691 assert(s->kind == FunctionDef_kind);
1692
1693 args = s->v.FunctionDef.args;
1694 returns = s->v.FunctionDef.returns;
1695 decos = s->v.FunctionDef.decorator_list;
1696 name = s->v.FunctionDef.name;
1697 body = s->v.FunctionDef.body;
1698
1699 scope_type = COMPILER_SCOPE_FUNCTION;
1700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (!compiler_decorators(c, decos))
1703 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001704 if (args->defaults)
1705 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (args->kwonlyargs) {
1707 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1708 args->kw_defaults);
1709 if (res < 0)
1710 return 0;
1711 kw_default_count = res;
1712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 num_annotations = compiler_visit_annotations(c, args, returns);
1714 if (num_annotations < 0)
1715 return 0;
1716 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001717
Yury Selivanov75445082015-05-11 22:57:16 -04001718 if (!compiler_enter_scope(c, name,
1719 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 s->lineno))
1721 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722
Yury Selivanov75445082015-05-11 22:57:16 -04001723 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001725 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 first_const = st->v.Expr.value->v.Str.s;
1727 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1728 compiler_exit_scope(c);
1729 return 0;
1730 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 c->u->u_argcount = asdl_seq_LEN(args->args);
1733 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001734 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 /* if there was a docstring, we need to skip the first statement */
1736 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001737 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 VISIT_IN_SCOPE(c, stmt, st);
1739 }
1740 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001741 qualname = c->u->u_qualname;
1742 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001744 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001745 Py_XDECREF(qualname);
1746 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001748 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 arglength = asdl_seq_LEN(args->defaults);
1751 arglength |= kw_default_count << 8;
1752 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001753 if (is_async)
1754 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001755 compiler_make_closure(c, co, arglength, qualname);
1756 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 /* decorators */
1760 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1761 ADDOP_I(c, CALL_FUNCTION, 1);
1762 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763
Yury Selivanov75445082015-05-11 22:57:16 -04001764 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765}
1766
1767static int
1768compiler_class(struct compiler *c, stmt_ty s)
1769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyCodeObject *co;
1771 PyObject *str;
1772 int i;
1773 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (!compiler_decorators(c, decos))
1776 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* ultimately generate code for:
1779 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1780 where:
1781 <func> is a function/closure created from the class body;
1782 it has a single argument (__locals__) where the dict
1783 (or MutableSequence) representing the locals is passed
1784 <name> is the class name
1785 <bases> is the positional arguments and *varargs argument
1786 <keywords> is the keyword arguments and **kwds argument
1787 This borrows from compiler_call.
1788 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001791 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1792 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 return 0;
1794 /* this block represents what we do in the new scope */
1795 {
1796 /* use the class name for name mangling */
1797 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001798 Py_SETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* load (global) __name__ ... */
1800 str = PyUnicode_InternFromString("__name__");
1801 if (!str || !compiler_nameop(c, str, Load)) {
1802 Py_XDECREF(str);
1803 compiler_exit_scope(c);
1804 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001805 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 Py_DECREF(str);
1807 /* ... and store it as __module__ */
1808 str = PyUnicode_InternFromString("__module__");
1809 if (!str || !compiler_nameop(c, str, Store)) {
1810 Py_XDECREF(str);
1811 compiler_exit_scope(c);
1812 return 0;
1813 }
1814 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001815 assert(c->u->u_qualname);
1816 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001817 str = PyUnicode_InternFromString("__qualname__");
1818 if (!str || !compiler_nameop(c, str, Store)) {
1819 Py_XDECREF(str);
1820 compiler_exit_scope(c);
1821 return 0;
1822 }
1823 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* compile the body proper */
1825 if (!compiler_body(c, s->v.ClassDef.body)) {
1826 compiler_exit_scope(c);
1827 return 0;
1828 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001829 if (c->u->u_ste->ste_needs_class_closure) {
1830 /* return the (empty) __class__ cell */
1831 str = PyUnicode_InternFromString("__class__");
1832 if (str == NULL) {
1833 compiler_exit_scope(c);
1834 return 0;
1835 }
1836 i = compiler_lookup_arg(c->u->u_cellvars, str);
1837 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001838 if (i < 0) {
1839 compiler_exit_scope(c);
1840 return 0;
1841 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001842 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 /* Return the cell where to store __class__ */
1844 ADDOP_I(c, LOAD_CLOSURE, i);
1845 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001846 else {
1847 assert(PyDict_Size(c->u->u_cellvars) == 0);
1848 /* This happens when nobody references the cell. Return None. */
1849 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1852 /* create the code object */
1853 co = assemble(c, 1);
1854 }
1855 /* leave the new scope */
1856 compiler_exit_scope(c);
1857 if (co == NULL)
1858 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* 2. load the 'build_class' function */
1861 ADDOP(c, LOAD_BUILD_CLASS);
1862
1863 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001864 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 Py_DECREF(co);
1866
1867 /* 4. load class name */
1868 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1869
1870 /* 5. generate the rest of the code for the call */
1871 if (!compiler_call_helper(c, 2,
1872 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001873 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 return 0;
1875
1876 /* 6. apply decorators */
1877 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1878 ADDOP_I(c, CALL_FUNCTION, 1);
1879 }
1880
1881 /* 7. store into <name> */
1882 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1883 return 0;
1884 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885}
1886
1887static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001888compiler_ifexp(struct compiler *c, expr_ty e)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 basicblock *end, *next;
1891
1892 assert(e->kind == IfExp_kind);
1893 end = compiler_new_block(c);
1894 if (end == NULL)
1895 return 0;
1896 next = compiler_new_block(c);
1897 if (next == NULL)
1898 return 0;
1899 VISIT(c, expr, e->v.IfExp.test);
1900 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1901 VISIT(c, expr, e->v.IfExp.body);
1902 ADDOP_JREL(c, JUMP_FORWARD, end);
1903 compiler_use_next_block(c, next);
1904 VISIT(c, expr, e->v.IfExp.orelse);
1905 compiler_use_next_block(c, end);
1906 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001907}
1908
1909static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910compiler_lambda(struct compiler *c, expr_ty e)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001913 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001915 int kw_default_count = 0;
1916 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 arguments_ty args = e->v.Lambda.args;
1918 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (!name) {
1921 name = PyUnicode_InternFromString("<lambda>");
1922 if (!name)
1923 return 0;
1924 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001926 if (args->defaults)
1927 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (args->kwonlyargs) {
1929 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1930 args->kw_defaults);
1931 if (res < 0) return 0;
1932 kw_default_count = res;
1933 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001934 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001935 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 /* Make None the first constant, so the lambda can't have a
1939 docstring. */
1940 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 c->u->u_argcount = asdl_seq_LEN(args->args);
1944 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1945 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1946 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001947 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 }
1949 else {
1950 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001951 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001953 qualname = c->u->u_qualname;
1954 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001956 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 arglength = asdl_seq_LEN(args->defaults);
1960 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001961 compiler_make_closure(c, co, arglength, qualname);
1962 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 Py_DECREF(co);
1964
1965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969compiler_if(struct compiler *c, stmt_ty s)
1970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 basicblock *end, *next;
1972 int constant;
1973 assert(s->kind == If_kind);
1974 end = compiler_new_block(c);
1975 if (end == NULL)
1976 return 0;
1977
Georg Brandl8334fd92010-12-04 10:26:46 +00001978 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* constant = 0: "if 0"
1980 * constant = 1: "if 1", "if 2", ...
1981 * constant = -1: rest */
1982 if (constant == 0) {
1983 if (s->v.If.orelse)
1984 VISIT_SEQ(c, stmt, s->v.If.orelse);
1985 } else if (constant == 1) {
1986 VISIT_SEQ(c, stmt, s->v.If.body);
1987 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001988 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 next = compiler_new_block(c);
1990 if (next == NULL)
1991 return 0;
1992 }
1993 else
1994 next = end;
1995 VISIT(c, expr, s->v.If.test);
1996 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1997 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001998 if (asdl_seq_LEN(s->v.If.orelse)) {
1999 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 compiler_use_next_block(c, next);
2001 VISIT_SEQ(c, stmt, s->v.If.orelse);
2002 }
2003 }
2004 compiler_use_next_block(c, end);
2005 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006}
2007
2008static int
2009compiler_for(struct compiler *c, stmt_ty s)
2010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 start = compiler_new_block(c);
2014 cleanup = compiler_new_block(c);
2015 end = compiler_new_block(c);
2016 if (start == NULL || end == NULL || cleanup == NULL)
2017 return 0;
2018 ADDOP_JREL(c, SETUP_LOOP, end);
2019 if (!compiler_push_fblock(c, LOOP, start))
2020 return 0;
2021 VISIT(c, expr, s->v.For.iter);
2022 ADDOP(c, GET_ITER);
2023 compiler_use_next_block(c, start);
2024 ADDOP_JREL(c, FOR_ITER, cleanup);
2025 VISIT(c, expr, s->v.For.target);
2026 VISIT_SEQ(c, stmt, s->v.For.body);
2027 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2028 compiler_use_next_block(c, cleanup);
2029 ADDOP(c, POP_BLOCK);
2030 compiler_pop_fblock(c, LOOP, start);
2031 VISIT_SEQ(c, stmt, s->v.For.orelse);
2032 compiler_use_next_block(c, end);
2033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
Yury Selivanov75445082015-05-11 22:57:16 -04002036
2037static int
2038compiler_async_for(struct compiler *c, stmt_ty s)
2039{
2040 static PyObject *stopiter_error = NULL;
2041 basicblock *try, *except, *end, *after_try, *try_cleanup,
2042 *after_loop, *after_loop_else;
2043
2044 if (stopiter_error == NULL) {
2045 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2046 if (stopiter_error == NULL)
2047 return 0;
2048 }
2049
2050 try = compiler_new_block(c);
2051 except = compiler_new_block(c);
2052 end = compiler_new_block(c);
2053 after_try = compiler_new_block(c);
2054 try_cleanup = compiler_new_block(c);
2055 after_loop = compiler_new_block(c);
2056 after_loop_else = compiler_new_block(c);
2057
2058 if (try == NULL || except == NULL || end == NULL
2059 || after_try == NULL || try_cleanup == NULL)
2060 return 0;
2061
2062 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2063 if (!compiler_push_fblock(c, LOOP, try))
2064 return 0;
2065
2066 VISIT(c, expr, s->v.AsyncFor.iter);
2067 ADDOP(c, GET_AITER);
2068 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2069 ADDOP(c, YIELD_FROM);
2070
2071 compiler_use_next_block(c, try);
2072
2073
2074 ADDOP_JREL(c, SETUP_EXCEPT, except);
2075 if (!compiler_push_fblock(c, EXCEPT, try))
2076 return 0;
2077
2078 ADDOP(c, GET_ANEXT);
2079 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2080 ADDOP(c, YIELD_FROM);
2081 VISIT(c, expr, s->v.AsyncFor.target);
2082 ADDOP(c, POP_BLOCK);
2083 compiler_pop_fblock(c, EXCEPT, try);
2084 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2085
2086
2087 compiler_use_next_block(c, except);
2088 ADDOP(c, DUP_TOP);
2089 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2090 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2091 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2092
2093 ADDOP(c, POP_TOP);
2094 ADDOP(c, POP_TOP);
2095 ADDOP(c, POP_TOP);
2096 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2097 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2098 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2099
2100
2101 compiler_use_next_block(c, try_cleanup);
2102 ADDOP(c, END_FINALLY);
2103
2104 compiler_use_next_block(c, after_try);
2105 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2106 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2107
2108 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2109 compiler_pop_fblock(c, LOOP, try);
2110
2111 compiler_use_next_block(c, after_loop);
2112 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2113
2114 compiler_use_next_block(c, after_loop_else);
2115 VISIT_SEQ(c, stmt, s->v.For.orelse);
2116
2117 compiler_use_next_block(c, end);
2118
2119 return 1;
2120}
2121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122static int
2123compiler_while(struct compiler *c, stmt_ty s)
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002126 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (constant == 0) {
2129 if (s->v.While.orelse)
2130 VISIT_SEQ(c, stmt, s->v.While.orelse);
2131 return 1;
2132 }
2133 loop = compiler_new_block(c);
2134 end = compiler_new_block(c);
2135 if (constant == -1) {
2136 anchor = compiler_new_block(c);
2137 if (anchor == NULL)
2138 return 0;
2139 }
2140 if (loop == NULL || end == NULL)
2141 return 0;
2142 if (s->v.While.orelse) {
2143 orelse = compiler_new_block(c);
2144 if (orelse == NULL)
2145 return 0;
2146 }
2147 else
2148 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 ADDOP_JREL(c, SETUP_LOOP, end);
2151 compiler_use_next_block(c, loop);
2152 if (!compiler_push_fblock(c, LOOP, loop))
2153 return 0;
2154 if (constant == -1) {
2155 VISIT(c, expr, s->v.While.test);
2156 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2157 }
2158 VISIT_SEQ(c, stmt, s->v.While.body);
2159 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 /* XXX should the two POP instructions be in a separate block
2162 if there is no else clause ?
2163 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002165 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002167 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 compiler_pop_fblock(c, LOOP, loop);
2169 if (orelse != NULL) /* what if orelse is just pass? */
2170 VISIT_SEQ(c, stmt, s->v.While.orelse);
2171 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174}
2175
2176static int
2177compiler_continue(struct compiler *c)
2178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2180 static const char IN_FINALLY_ERROR_MSG[] =
2181 "'continue' not supported inside 'finally' clause";
2182 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (!c->u->u_nfblocks)
2185 return compiler_error(c, LOOP_ERROR_MSG);
2186 i = c->u->u_nfblocks - 1;
2187 switch (c->u->u_fblock[i].fb_type) {
2188 case LOOP:
2189 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2190 break;
2191 case EXCEPT:
2192 case FINALLY_TRY:
2193 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2194 /* Prevent continue anywhere under a finally
2195 even if hidden in a sub-try or except. */
2196 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2197 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2198 }
2199 if (i == -1)
2200 return compiler_error(c, LOOP_ERROR_MSG);
2201 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2202 break;
2203 case FINALLY_END:
2204 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2205 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208}
2209
2210/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211
2212 SETUP_FINALLY L
2213 <code for body>
2214 POP_BLOCK
2215 LOAD_CONST <None>
2216 L: <code for finalbody>
2217 END_FINALLY
2218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219 The special instructions use the block stack. Each block
2220 stack entry contains the instruction that created it (here
2221 SETUP_FINALLY), the level of the value stack at the time the
2222 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 Pushes the current value stack level and the label
2226 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 Pops en entry from the block stack, and pops the value
2229 stack until its level is the same as indicated on the
2230 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 Pops a variable number of entries from the *value* stack
2233 and re-raises the exception they specify. The number of
2234 entries popped depends on the (pseudo) exception type.
2235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236 The block stack is unwound when an exception is raised:
2237 when a SETUP_FINALLY entry is found, the exception is pushed
2238 onto the value stack (and the exception condition is cleared),
2239 and the interpreter jumps to the label gotten from the block
2240 stack.
2241*/
2242
2243static int
2244compiler_try_finally(struct compiler *c, stmt_ty s)
2245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 basicblock *body, *end;
2247 body = compiler_new_block(c);
2248 end = compiler_new_block(c);
2249 if (body == NULL || end == NULL)
2250 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 ADDOP_JREL(c, SETUP_FINALLY, end);
2253 compiler_use_next_block(c, body);
2254 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2255 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002256 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2257 if (!compiler_try_except(c, s))
2258 return 0;
2259 }
2260 else {
2261 VISIT_SEQ(c, stmt, s->v.Try.body);
2262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 ADDOP(c, POP_BLOCK);
2264 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2267 compiler_use_next_block(c, end);
2268 if (!compiler_push_fblock(c, FINALLY_END, end))
2269 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002270 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 ADDOP(c, END_FINALLY);
2272 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275}
2276
2277/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002278 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 (The contents of the value stack is shown in [], with the top
2280 at the right; 'tb' is trace-back info, 'val' the exception's
2281 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282
2283 Value stack Label Instruction Argument
2284 [] SETUP_EXCEPT L1
2285 [] <code for S>
2286 [] POP_BLOCK
2287 [] JUMP_FORWARD L0
2288
2289 [tb, val, exc] L1: DUP )
2290 [tb, val, exc, exc] <evaluate E1> )
2291 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2292 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2293 [tb, val, exc] POP
2294 [tb, val] <assign to V1> (or POP if no V1)
2295 [tb] POP
2296 [] <code for S1>
2297 JUMP_FORWARD L0
2298
2299 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 .............................etc.......................
2301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2303
2304 [] L0: <next statement>
2305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 Of course, parts are not generated if Vi or Ei is not present.
2307*/
2308static int
2309compiler_try_except(struct compiler *c, stmt_ty s)
2310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002312 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 body = compiler_new_block(c);
2315 except = compiler_new_block(c);
2316 orelse = compiler_new_block(c);
2317 end = compiler_new_block(c);
2318 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2319 return 0;
2320 ADDOP_JREL(c, SETUP_EXCEPT, except);
2321 compiler_use_next_block(c, body);
2322 if (!compiler_push_fblock(c, EXCEPT, body))
2323 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002324 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 ADDOP(c, POP_BLOCK);
2326 compiler_pop_fblock(c, EXCEPT, body);
2327 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002328 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 compiler_use_next_block(c, except);
2330 for (i = 0; i < n; i++) {
2331 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002332 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (!handler->v.ExceptHandler.type && i < n-1)
2334 return compiler_error(c, "default 'except:' must be last");
2335 c->u->u_lineno_set = 0;
2336 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002337 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 except = compiler_new_block(c);
2339 if (except == NULL)
2340 return 0;
2341 if (handler->v.ExceptHandler.type) {
2342 ADDOP(c, DUP_TOP);
2343 VISIT(c, expr, handler->v.ExceptHandler.type);
2344 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2345 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2346 }
2347 ADDOP(c, POP_TOP);
2348 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002349 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002350
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002351 cleanup_end = compiler_new_block(c);
2352 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002353 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002354 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002355
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002356 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2357 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002359 /*
2360 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002361 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002362 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002363 try:
2364 # body
2365 finally:
2366 name = None
2367 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002368 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002370 /* second try: */
2371 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2372 compiler_use_next_block(c, cleanup_body);
2373 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2374 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002376 /* second # body */
2377 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2378 ADDOP(c, POP_BLOCK);
2379 ADDOP(c, POP_EXCEPT);
2380 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002382 /* finally: */
2383 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2384 compiler_use_next_block(c, cleanup_end);
2385 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2386 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002388 /* name = None */
2389 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2390 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002392 /* del name */
2393 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002395 ADDOP(c, END_FINALLY);
2396 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 }
2398 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002399 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002401 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002402 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002403 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404
Guido van Rossumb940e112007-01-10 16:19:56 +00002405 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002406 ADDOP(c, POP_TOP);
2407 compiler_use_next_block(c, cleanup_body);
2408 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2409 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002411 ADDOP(c, POP_EXCEPT);
2412 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 }
2414 ADDOP_JREL(c, JUMP_FORWARD, end);
2415 compiler_use_next_block(c, except);
2416 }
2417 ADDOP(c, END_FINALLY);
2418 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002419 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 compiler_use_next_block(c, end);
2421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422}
2423
2424static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002425compiler_try(struct compiler *c, stmt_ty s) {
2426 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2427 return compiler_try_finally(c, s);
2428 else
2429 return compiler_try_except(c, s);
2430}
2431
2432
2433static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434compiler_import_as(struct compiler *c, identifier name, identifier asname)
2435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 /* The IMPORT_NAME opcode was already generated. This function
2437 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 If there is a dot in name, we need to split it and emit a
2440 LOAD_ATTR for each name.
2441 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2443 PyUnicode_GET_LENGTH(name), 1);
2444 if (dot == -2)
2445 return -1;
2446 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 Py_ssize_t pos = dot + 1;
2449 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 dot = PyUnicode_FindChar(name, '.', pos,
2452 PyUnicode_GET_LENGTH(name), 1);
2453 if (dot == -2)
2454 return -1;
2455 attr = PyUnicode_Substring(name, pos,
2456 (dot != -1) ? dot :
2457 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (!attr)
2459 return -1;
2460 ADDOP_O(c, LOAD_ATTR, attr, names);
2461 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 }
2464 }
2465 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466}
2467
2468static int
2469compiler_import(struct compiler *c, stmt_ty s)
2470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 /* The Import node stores a module name like a.b.c as a single
2472 string. This is convenient for all cases except
2473 import a.b.c as d
2474 where we need to parse that string to extract the individual
2475 module names.
2476 XXX Perhaps change the representation to make this case simpler?
2477 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002478 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 for (i = 0; i < n; i++) {
2481 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2482 int r;
2483 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 level = PyLong_FromLong(0);
2486 if (level == NULL)
2487 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 ADDOP_O(c, LOAD_CONST, level, consts);
2490 Py_DECREF(level);
2491 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2492 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (alias->asname) {
2495 r = compiler_import_as(c, alias->name, alias->asname);
2496 if (!r)
2497 return r;
2498 }
2499 else {
2500 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 Py_ssize_t dot = PyUnicode_FindChar(
2502 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002503 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002505 if (tmp == NULL)
2506 return 0;
2507 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_DECREF(tmp);
2511 }
2512 if (!r)
2513 return r;
2514 }
2515 }
2516 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517}
2518
2519static int
2520compiler_from_import(struct compiler *c, stmt_ty s)
2521{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002522 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 PyObject *names = PyTuple_New(n);
2525 PyObject *level;
2526 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 if (!empty_string) {
2529 empty_string = PyUnicode_FromString("");
2530 if (!empty_string)
2531 return 0;
2532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (!names)
2535 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 level = PyLong_FromLong(s->v.ImportFrom.level);
2538 if (!level) {
2539 Py_DECREF(names);
2540 return 0;
2541 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* build up the names */
2544 for (i = 0; i < n; i++) {
2545 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2546 Py_INCREF(alias->name);
2547 PyTuple_SET_ITEM(names, i, alias->name);
2548 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2551 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2552 Py_DECREF(level);
2553 Py_DECREF(names);
2554 return compiler_error(c, "from __future__ imports must occur "
2555 "at the beginning of the file");
2556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 ADDOP_O(c, LOAD_CONST, level, consts);
2559 Py_DECREF(level);
2560 ADDOP_O(c, LOAD_CONST, names, consts);
2561 Py_DECREF(names);
2562 if (s->v.ImportFrom.module) {
2563 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2564 }
2565 else {
2566 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2567 }
2568 for (i = 0; i < n; i++) {
2569 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2570 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 assert(n == 1);
2574 ADDOP(c, IMPORT_STAR);
2575 return 1;
2576 }
2577
2578 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2579 store_name = alias->name;
2580 if (alias->asname)
2581 store_name = alias->asname;
2582
2583 if (!compiler_nameop(c, store_name, Store)) {
2584 Py_DECREF(names);
2585 return 0;
2586 }
2587 }
2588 /* remove imported module */
2589 ADDOP(c, POP_TOP);
2590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591}
2592
2593static int
2594compiler_assert(struct compiler *c, stmt_ty s)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 static PyObject *assertion_error = NULL;
2597 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002598 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599
Georg Brandl8334fd92010-12-04 10:26:46 +00002600 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 return 1;
2602 if (assertion_error == NULL) {
2603 assertion_error = PyUnicode_InternFromString("AssertionError");
2604 if (assertion_error == NULL)
2605 return 0;
2606 }
2607 if (s->v.Assert.test->kind == Tuple_kind &&
2608 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002609 msg = PyUnicode_FromString("assertion is always true, "
2610 "perhaps remove parentheses?");
2611 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002613 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2614 c->c_filename, c->u->u_lineno,
2615 NULL, NULL) == -1) {
2616 Py_DECREF(msg);
2617 return 0;
2618 }
2619 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 }
2621 VISIT(c, expr, s->v.Assert.test);
2622 end = compiler_new_block(c);
2623 if (end == NULL)
2624 return 0;
2625 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2626 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2627 if (s->v.Assert.msg) {
2628 VISIT(c, expr, s->v.Assert.msg);
2629 ADDOP_I(c, CALL_FUNCTION, 1);
2630 }
2631 ADDOP_I(c, RAISE_VARARGS, 1);
2632 compiler_use_next_block(c, end);
2633 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634}
2635
2636static int
2637compiler_visit_stmt(struct compiler *c, stmt_ty s)
2638{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002639 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 /* Always assign a lineno to the next instruction for a stmt. */
2642 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002643 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 switch (s->kind) {
2647 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002648 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 case ClassDef_kind:
2650 return compiler_class(c, s);
2651 case Return_kind:
2652 if (c->u->u_ste->ste_type != FunctionBlock)
2653 return compiler_error(c, "'return' outside function");
2654 if (s->v.Return.value) {
2655 VISIT(c, expr, s->v.Return.value);
2656 }
2657 else
2658 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2659 ADDOP(c, RETURN_VALUE);
2660 break;
2661 case Delete_kind:
2662 VISIT_SEQ(c, expr, s->v.Delete.targets)
2663 break;
2664 case Assign_kind:
2665 n = asdl_seq_LEN(s->v.Assign.targets);
2666 VISIT(c, expr, s->v.Assign.value);
2667 for (i = 0; i < n; i++) {
2668 if (i < n - 1)
2669 ADDOP(c, DUP_TOP);
2670 VISIT(c, expr,
2671 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2672 }
2673 break;
2674 case AugAssign_kind:
2675 return compiler_augassign(c, s);
2676 case For_kind:
2677 return compiler_for(c, s);
2678 case While_kind:
2679 return compiler_while(c, s);
2680 case If_kind:
2681 return compiler_if(c, s);
2682 case Raise_kind:
2683 n = 0;
2684 if (s->v.Raise.exc) {
2685 VISIT(c, expr, s->v.Raise.exc);
2686 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002687 if (s->v.Raise.cause) {
2688 VISIT(c, expr, s->v.Raise.cause);
2689 n++;
2690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002692 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002694 case Try_kind:
2695 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 case Assert_kind:
2697 return compiler_assert(c, s);
2698 case Import_kind:
2699 return compiler_import(c, s);
2700 case ImportFrom_kind:
2701 return compiler_from_import(c, s);
2702 case Global_kind:
2703 case Nonlocal_kind:
2704 break;
2705 case Expr_kind:
2706 if (c->c_interactive && c->c_nestlevel <= 1) {
2707 VISIT(c, expr, s->v.Expr.value);
2708 ADDOP(c, PRINT_EXPR);
2709 }
2710 else if (s->v.Expr.value->kind != Str_kind &&
2711 s->v.Expr.value->kind != Num_kind) {
2712 VISIT(c, expr, s->v.Expr.value);
2713 ADDOP(c, POP_TOP);
2714 }
2715 break;
2716 case Pass_kind:
2717 break;
2718 case Break_kind:
2719 if (!compiler_in_loop(c))
2720 return compiler_error(c, "'break' outside loop");
2721 ADDOP(c, BREAK_LOOP);
2722 break;
2723 case Continue_kind:
2724 return compiler_continue(c);
2725 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002726 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002727 case AsyncFunctionDef_kind:
2728 return compiler_function(c, s, 1);
2729 case AsyncWith_kind:
2730 return compiler_async_with(c, s, 0);
2731 case AsyncFor_kind:
2732 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 }
Yury Selivanov75445082015-05-11 22:57:16 -04002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736}
2737
2738static int
2739unaryop(unaryop_ty op)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 switch (op) {
2742 case Invert:
2743 return UNARY_INVERT;
2744 case Not:
2745 return UNARY_NOT;
2746 case UAdd:
2747 return UNARY_POSITIVE;
2748 case USub:
2749 return UNARY_NEGATIVE;
2750 default:
2751 PyErr_Format(PyExc_SystemError,
2752 "unary op %d should not be possible", op);
2753 return 0;
2754 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755}
2756
2757static int
2758binop(struct compiler *c, operator_ty op)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 switch (op) {
2761 case Add:
2762 return BINARY_ADD;
2763 case Sub:
2764 return BINARY_SUBTRACT;
2765 case Mult:
2766 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002767 case MatMult:
2768 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 case Div:
2770 return BINARY_TRUE_DIVIDE;
2771 case Mod:
2772 return BINARY_MODULO;
2773 case Pow:
2774 return BINARY_POWER;
2775 case LShift:
2776 return BINARY_LSHIFT;
2777 case RShift:
2778 return BINARY_RSHIFT;
2779 case BitOr:
2780 return BINARY_OR;
2781 case BitXor:
2782 return BINARY_XOR;
2783 case BitAnd:
2784 return BINARY_AND;
2785 case FloorDiv:
2786 return BINARY_FLOOR_DIVIDE;
2787 default:
2788 PyErr_Format(PyExc_SystemError,
2789 "binary op %d should not be possible", op);
2790 return 0;
2791 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792}
2793
2794static int
2795cmpop(cmpop_ty op)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 switch (op) {
2798 case Eq:
2799 return PyCmp_EQ;
2800 case NotEq:
2801 return PyCmp_NE;
2802 case Lt:
2803 return PyCmp_LT;
2804 case LtE:
2805 return PyCmp_LE;
2806 case Gt:
2807 return PyCmp_GT;
2808 case GtE:
2809 return PyCmp_GE;
2810 case Is:
2811 return PyCmp_IS;
2812 case IsNot:
2813 return PyCmp_IS_NOT;
2814 case In:
2815 return PyCmp_IN;
2816 case NotIn:
2817 return PyCmp_NOT_IN;
2818 default:
2819 return PyCmp_BAD;
2820 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821}
2822
2823static int
2824inplace_binop(struct compiler *c, operator_ty op)
2825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 switch (op) {
2827 case Add:
2828 return INPLACE_ADD;
2829 case Sub:
2830 return INPLACE_SUBTRACT;
2831 case Mult:
2832 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002833 case MatMult:
2834 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 case Div:
2836 return INPLACE_TRUE_DIVIDE;
2837 case Mod:
2838 return INPLACE_MODULO;
2839 case Pow:
2840 return INPLACE_POWER;
2841 case LShift:
2842 return INPLACE_LSHIFT;
2843 case RShift:
2844 return INPLACE_RSHIFT;
2845 case BitOr:
2846 return INPLACE_OR;
2847 case BitXor:
2848 return INPLACE_XOR;
2849 case BitAnd:
2850 return INPLACE_AND;
2851 case FloorDiv:
2852 return INPLACE_FLOOR_DIVIDE;
2853 default:
2854 PyErr_Format(PyExc_SystemError,
2855 "inplace binary op %d should not be possible", op);
2856 return 0;
2857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858}
2859
2860static int
2861compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2862{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002863 int op, scope;
2864 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 PyObject *dict = c->u->u_names;
2868 PyObject *mangled;
2869 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 mangled = _Py_Mangle(c->u->u_private, name);
2872 if (!mangled)
2873 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002874
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002875 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2876 PyUnicode_CompareWithASCIIString(name, "True") &&
2877 PyUnicode_CompareWithASCIIString(name, "False"));
2878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 op = 0;
2880 optype = OP_NAME;
2881 scope = PyST_GetScope(c->u->u_ste, mangled);
2882 switch (scope) {
2883 case FREE:
2884 dict = c->u->u_freevars;
2885 optype = OP_DEREF;
2886 break;
2887 case CELL:
2888 dict = c->u->u_cellvars;
2889 optype = OP_DEREF;
2890 break;
2891 case LOCAL:
2892 if (c->u->u_ste->ste_type == FunctionBlock)
2893 optype = OP_FAST;
2894 break;
2895 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002896 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 optype = OP_GLOBAL;
2898 break;
2899 case GLOBAL_EXPLICIT:
2900 optype = OP_GLOBAL;
2901 break;
2902 default:
2903 /* scope can be 0 */
2904 break;
2905 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002908 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 switch (optype) {
2911 case OP_DEREF:
2912 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002913 case Load:
2914 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2915 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 case Store: op = STORE_DEREF; break;
2917 case AugLoad:
2918 case AugStore:
2919 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002920 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 case Param:
2922 default:
2923 PyErr_SetString(PyExc_SystemError,
2924 "param invalid for deref variable");
2925 return 0;
2926 }
2927 break;
2928 case OP_FAST:
2929 switch (ctx) {
2930 case Load: op = LOAD_FAST; break;
2931 case Store: op = STORE_FAST; break;
2932 case Del: op = DELETE_FAST; break;
2933 case AugLoad:
2934 case AugStore:
2935 break;
2936 case Param:
2937 default:
2938 PyErr_SetString(PyExc_SystemError,
2939 "param invalid for local variable");
2940 return 0;
2941 }
2942 ADDOP_O(c, op, mangled, varnames);
2943 Py_DECREF(mangled);
2944 return 1;
2945 case OP_GLOBAL:
2946 switch (ctx) {
2947 case Load: op = LOAD_GLOBAL; break;
2948 case Store: op = STORE_GLOBAL; break;
2949 case Del: op = DELETE_GLOBAL; break;
2950 case AugLoad:
2951 case AugStore:
2952 break;
2953 case Param:
2954 default:
2955 PyErr_SetString(PyExc_SystemError,
2956 "param invalid for global variable");
2957 return 0;
2958 }
2959 break;
2960 case OP_NAME:
2961 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002962 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 case Store: op = STORE_NAME; break;
2964 case Del: op = DELETE_NAME; break;
2965 case AugLoad:
2966 case AugStore:
2967 break;
2968 case Param:
2969 default:
2970 PyErr_SetString(PyExc_SystemError,
2971 "param invalid for name variable");
2972 return 0;
2973 }
2974 break;
2975 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 assert(op);
2978 arg = compiler_add_o(c, dict, mangled);
2979 Py_DECREF(mangled);
2980 if (arg < 0)
2981 return 0;
2982 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985static int
2986compiler_boolop(struct compiler *c, expr_ty e)
2987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002989 int jumpi;
2990 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 assert(e->kind == BoolOp_kind);
2994 if (e->v.BoolOp.op == And)
2995 jumpi = JUMP_IF_FALSE_OR_POP;
2996 else
2997 jumpi = JUMP_IF_TRUE_OR_POP;
2998 end = compiler_new_block(c);
2999 if (end == NULL)
3000 return 0;
3001 s = e->v.BoolOp.values;
3002 n = asdl_seq_LEN(s) - 1;
3003 assert(n >= 0);
3004 for (i = 0; i < n; ++i) {
3005 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3006 ADDOP_JABS(c, jumpi, end);
3007 }
3008 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3009 compiler_use_next_block(c, end);
3010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011}
3012
3013static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003014starunpack_helper(struct compiler *c, asdl_seq *elts,
3015 int single_op, int inner_op, int outer_op)
3016{
3017 Py_ssize_t n = asdl_seq_LEN(elts);
3018 Py_ssize_t i, nsubitems = 0, nseen = 0;
3019 for (i = 0; i < n; i++) {
3020 expr_ty elt = asdl_seq_GET(elts, i);
3021 if (elt->kind == Starred_kind) {
3022 if (nseen) {
3023 ADDOP_I(c, inner_op, nseen);
3024 nseen = 0;
3025 nsubitems++;
3026 }
3027 VISIT(c, expr, elt->v.Starred.value);
3028 nsubitems++;
3029 }
3030 else {
3031 VISIT(c, expr, elt);
3032 nseen++;
3033 }
3034 }
3035 if (nsubitems) {
3036 if (nseen) {
3037 ADDOP_I(c, inner_op, nseen);
3038 nsubitems++;
3039 }
3040 ADDOP_I(c, outer_op, nsubitems);
3041 }
3042 else
3043 ADDOP_I(c, single_op, nseen);
3044 return 1;
3045}
3046
3047static int
3048assignment_helper(struct compiler *c, asdl_seq *elts)
3049{
3050 Py_ssize_t n = asdl_seq_LEN(elts);
3051 Py_ssize_t i;
3052 int seen_star = 0;
3053 for (i = 0; i < n; i++) {
3054 expr_ty elt = asdl_seq_GET(elts, i);
3055 if (elt->kind == Starred_kind && !seen_star) {
3056 if ((i >= (1 << 8)) ||
3057 (n-i-1 >= (INT_MAX >> 8)))
3058 return compiler_error(c,
3059 "too many expressions in "
3060 "star-unpacking assignment");
3061 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3062 seen_star = 1;
3063 asdl_seq_SET(elts, i, elt->v.Starred.value);
3064 }
3065 else if (elt->kind == Starred_kind) {
3066 return compiler_error(c,
3067 "two starred expressions in assignment");
3068 }
3069 }
3070 if (!seen_star) {
3071 ADDOP_I(c, UNPACK_SEQUENCE, n);
3072 }
3073 VISIT_SEQ(c, expr, elts);
3074 return 1;
3075}
3076
3077static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078compiler_list(struct compiler *c, expr_ty e)
3079{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003080 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003082 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003084 else if (e->v.List.ctx == Load) {
3085 return starunpack_helper(c, elts,
3086 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003088 else
3089 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091}
3092
3093static int
3094compiler_tuple(struct compiler *c, expr_ty e)
3095{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003096 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003098 return assignment_helper(c, elts);
3099 }
3100 else if (e->v.Tuple.ctx == Load) {
3101 return starunpack_helper(c, elts,
3102 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3103 }
3104 else
3105 VISIT_SEQ(c, expr, elts);
3106 return 1;
3107}
3108
3109static int
3110compiler_set(struct compiler *c, expr_ty e)
3111{
3112 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3113 BUILD_SET, BUILD_SET_UNPACK);
3114}
3115
3116static int
3117compiler_dict(struct compiler *c, expr_ty e)
3118{
3119 Py_ssize_t i, n, containers, elements;
3120 int is_unpacking = 0;
3121 n = asdl_seq_LEN(e->v.Dict.values);
3122 containers = 0;
3123 elements = 0;
3124 for (i = 0; i < n; i++) {
3125 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3126 if (elements == 0xFFFF || (elements && is_unpacking)) {
3127 ADDOP_I(c, BUILD_MAP, elements);
3128 containers++;
3129 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003131 if (is_unpacking) {
3132 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3133 containers++;
3134 }
3135 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003136 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003137 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003138 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 }
3140 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003141 if (elements || containers == 0) {
3142 ADDOP_I(c, BUILD_MAP, elements);
3143 containers++;
3144 }
3145 /* If there is more than one dict, they need to be merged into a new
3146 * dict. If there is one dict and it's an unpacking, then it needs
3147 * to be copied into a new dict." */
3148 while (containers > 1 || is_unpacking) {
3149 int oparg = containers < 255 ? containers : 255;
3150 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3151 containers -= (oparg - 1);
3152 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 }
3154 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155}
3156
3157static int
3158compiler_compare(struct compiler *c, expr_ty e)
3159{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003160 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3164 VISIT(c, expr, e->v.Compare.left);
3165 n = asdl_seq_LEN(e->v.Compare.ops);
3166 assert(n > 0);
3167 if (n > 1) {
3168 cleanup = compiler_new_block(c);
3169 if (cleanup == NULL)
3170 return 0;
3171 VISIT(c, expr,
3172 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3173 }
3174 for (i = 1; i < n; i++) {
3175 ADDOP(c, DUP_TOP);
3176 ADDOP(c, ROT_THREE);
3177 ADDOP_I(c, COMPARE_OP,
3178 cmpop((cmpop_ty)(asdl_seq_GET(
3179 e->v.Compare.ops, i - 1))));
3180 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3181 NEXT_BLOCK(c);
3182 if (i < (n - 1))
3183 VISIT(c, expr,
3184 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3185 }
3186 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3187 ADDOP_I(c, COMPARE_OP,
3188 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3189 if (n > 1) {
3190 basicblock *end = compiler_new_block(c);
3191 if (end == NULL)
3192 return 0;
3193 ADDOP_JREL(c, JUMP_FORWARD, end);
3194 compiler_use_next_block(c, cleanup);
3195 ADDOP(c, ROT_TWO);
3196 ADDOP(c, POP_TOP);
3197 compiler_use_next_block(c, end);
3198 }
3199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200}
3201
3202static int
3203compiler_call(struct compiler *c, expr_ty e)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 VISIT(c, expr, e->v.Call.func);
3206 return compiler_call_helper(c, 0,
3207 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003208 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003209}
3210
3211/* shared code between compiler_call and compiler_class */
3212static int
3213compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003214 Py_ssize_t n, /* Args already pushed */
3215 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003216 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003219 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003220
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003221 /* the number of tuples and dictionaries on the stack */
3222 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3223
3224 nkw = 0;
3225 nseen = 0; /* the number of positional arguments on the stack */
3226 nelts = asdl_seq_LEN(args);
3227 for (i = 0; i < nelts; i++) {
3228 expr_ty elt = asdl_seq_GET(args, i);
3229 if (elt->kind == Starred_kind) {
3230 /* A star-arg. If we've seen positional arguments,
3231 pack the positional arguments into a
3232 tuple. */
3233 if (nseen) {
3234 ADDOP_I(c, BUILD_TUPLE, nseen);
3235 nseen = 0;
3236 nsubargs++;
3237 }
3238 VISIT(c, expr, elt->v.Starred.value);
3239 nsubargs++;
3240 }
3241 else if (nsubargs) {
3242 /* We've seen star-args already, so we
3243 count towards items-to-pack-into-tuple. */
3244 VISIT(c, expr, elt);
3245 nseen++;
3246 }
3247 else {
3248 /* Positional arguments before star-arguments
3249 are left on the stack. */
3250 VISIT(c, expr, elt);
3251 n++;
3252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003254 if (nseen) {
3255 /* Pack up any trailing positional arguments. */
3256 ADDOP_I(c, BUILD_TUPLE, nseen);
3257 nsubargs++;
3258 }
3259 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003261 if (nsubargs > 1) {
3262 /* If we ended up with more than one stararg, we need
3263 to concatenate them into a single sequence. */
3264 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003267
3268 /* Same dance again for keyword arguments */
3269 nseen = 0; /* the number of keyword arguments on the stack following */
3270 nelts = asdl_seq_LEN(keywords);
3271 for (i = 0; i < nelts; i++) {
3272 keyword_ty kw = asdl_seq_GET(keywords, i);
3273 if (kw->arg == NULL) {
3274 /* A keyword argument unpacking. */
3275 if (nseen) {
3276 ADDOP_I(c, BUILD_MAP, nseen);
3277 nseen = 0;
3278 nsubkwargs++;
3279 }
3280 VISIT(c, expr, kw->value);
3281 nsubkwargs++;
3282 }
3283 else if (nsubkwargs) {
3284 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003285 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003286 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003287 nseen++;
3288 }
3289 else {
3290 /* keyword argument */
3291 VISIT(c, keyword, kw)
3292 nkw++;
3293 }
3294 }
3295 if (nseen) {
3296 /* Pack up any trailing keyword arguments. */
3297 ADDOP_I(c, BUILD_MAP, nseen);
3298 nsubkwargs++;
3299 }
3300 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003302 if (nsubkwargs > 1) {
3303 /* Pack it all up */
3304 int function_pos = n + (code & 1) + nkw + 1;
3305 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003308 assert(n < 1<<8);
3309 assert(nkw < 1<<24);
3310 n |= nkw << 8;
3311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 switch (code) {
3313 case 0:
3314 ADDOP_I(c, CALL_FUNCTION, n);
3315 break;
3316 case 1:
3317 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3318 break;
3319 case 2:
3320 ADDOP_I(c, CALL_FUNCTION_KW, n);
3321 break;
3322 case 3:
3323 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3324 break;
3325 }
3326 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327}
3328
Nick Coghlan650f0d02007-04-15 12:05:43 +00003329
3330/* List and set comprehensions and generator expressions work by creating a
3331 nested function to perform the actual iteration. This means that the
3332 iteration variables don't leak into the current scope.
3333 The defined function is called immediately following its definition, with the
3334 result of that call being the result of the expression.
3335 The LC/SC version returns the populated container, while the GE version is
3336 flagged in symtable.c as a generator, so it returns the generator object
3337 when the function is called.
3338 This code *knows* that the loop cannot contain break, continue, or return,
3339 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3340
3341 Possible cleanups:
3342 - iterate over the generator sequence instead of using recursion
3343*/
3344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346compiler_comprehension_generator(struct compiler *c,
3347 asdl_seq *generators, int gen_index,
3348 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 /* generate code for the iterator, then each of the ifs,
3351 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 comprehension_ty gen;
3354 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003355 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 start = compiler_new_block(c);
3358 skip = compiler_new_block(c);
3359 if_cleanup = compiler_new_block(c);
3360 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3363 anchor == NULL)
3364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 if (gen_index == 0) {
3369 /* Receive outermost iter as an implicit argument */
3370 c->u->u_argcount = 1;
3371 ADDOP_I(c, LOAD_FAST, 0);
3372 }
3373 else {
3374 /* Sub-iter - calculate on the fly */
3375 VISIT(c, expr, gen->iter);
3376 ADDOP(c, GET_ITER);
3377 }
3378 compiler_use_next_block(c, start);
3379 ADDOP_JREL(c, FOR_ITER, anchor);
3380 NEXT_BLOCK(c);
3381 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* XXX this needs to be cleaned up...a lot! */
3384 n = asdl_seq_LEN(gen->ifs);
3385 for (i = 0; i < n; i++) {
3386 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3387 VISIT(c, expr, e);
3388 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3389 NEXT_BLOCK(c);
3390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 if (++gen_index < asdl_seq_LEN(generators))
3393 if (!compiler_comprehension_generator(c,
3394 generators, gen_index,
3395 elt, val, type))
3396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 /* only append after the last for generator */
3399 if (gen_index >= asdl_seq_LEN(generators)) {
3400 /* comprehension specific code */
3401 switch (type) {
3402 case COMP_GENEXP:
3403 VISIT(c, expr, elt);
3404 ADDOP(c, YIELD_VALUE);
3405 ADDOP(c, POP_TOP);
3406 break;
3407 case COMP_LISTCOMP:
3408 VISIT(c, expr, elt);
3409 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3410 break;
3411 case COMP_SETCOMP:
3412 VISIT(c, expr, elt);
3413 ADDOP_I(c, SET_ADD, gen_index + 1);
3414 break;
3415 case COMP_DICTCOMP:
3416 /* With 'd[k] = v', v is evaluated before k, so we do
3417 the same. */
3418 VISIT(c, expr, val);
3419 VISIT(c, expr, elt);
3420 ADDOP_I(c, MAP_ADD, gen_index + 1);
3421 break;
3422 default:
3423 return 0;
3424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 compiler_use_next_block(c, skip);
3427 }
3428 compiler_use_next_block(c, if_cleanup);
3429 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3430 compiler_use_next_block(c, anchor);
3431
3432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433}
3434
3435static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003436compiler_comprehension(struct compiler *c, expr_ty e, int type,
3437 identifier name, asdl_seq *generators, expr_ty elt,
3438 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 PyCodeObject *co = NULL;
3441 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003442 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 outermost_iter = ((comprehension_ty)
3445 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003446
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003447 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3448 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 if (type != COMP_GENEXP) {
3452 int op;
3453 switch (type) {
3454 case COMP_LISTCOMP:
3455 op = BUILD_LIST;
3456 break;
3457 case COMP_SETCOMP:
3458 op = BUILD_SET;
3459 break;
3460 case COMP_DICTCOMP:
3461 op = BUILD_MAP;
3462 break;
3463 default:
3464 PyErr_Format(PyExc_SystemError,
3465 "unknown comprehension type %d", type);
3466 goto error_in_scope;
3467 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 ADDOP_I(c, op, 0);
3470 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 if (!compiler_comprehension_generator(c, generators, 0, elt,
3473 val, type))
3474 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (type != COMP_GENEXP) {
3477 ADDOP(c, RETURN_VALUE);
3478 }
3479
3480 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003481 qualname = c->u->u_qualname;
3482 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003484 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 goto error;
3486
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003487 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003489 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 Py_DECREF(co);
3491
3492 VISIT(c, expr, outermost_iter);
3493 ADDOP(c, GET_ITER);
3494 ADDOP_I(c, CALL_FUNCTION, 1);
3495 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003496error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003498error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003499 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 Py_XDECREF(co);
3501 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003502}
3503
3504static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505compiler_genexp(struct compiler *c, expr_ty e)
3506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 static identifier name;
3508 if (!name) {
3509 name = PyUnicode_FromString("<genexpr>");
3510 if (!name)
3511 return 0;
3512 }
3513 assert(e->kind == GeneratorExp_kind);
3514 return compiler_comprehension(c, e, COMP_GENEXP, name,
3515 e->v.GeneratorExp.generators,
3516 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517}
3518
3519static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003520compiler_listcomp(struct compiler *c, expr_ty e)
3521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 static identifier name;
3523 if (!name) {
3524 name = PyUnicode_FromString("<listcomp>");
3525 if (!name)
3526 return 0;
3527 }
3528 assert(e->kind == ListComp_kind);
3529 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3530 e->v.ListComp.generators,
3531 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003532}
3533
3534static int
3535compiler_setcomp(struct compiler *c, expr_ty e)
3536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 static identifier name;
3538 if (!name) {
3539 name = PyUnicode_FromString("<setcomp>");
3540 if (!name)
3541 return 0;
3542 }
3543 assert(e->kind == SetComp_kind);
3544 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3545 e->v.SetComp.generators,
3546 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003547}
3548
3549
3550static int
3551compiler_dictcomp(struct compiler *c, expr_ty e)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 static identifier name;
3554 if (!name) {
3555 name = PyUnicode_FromString("<dictcomp>");
3556 if (!name)
3557 return 0;
3558 }
3559 assert(e->kind == DictComp_kind);
3560 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3561 e->v.DictComp.generators,
3562 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003563}
3564
3565
3566static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567compiler_visit_keyword(struct compiler *c, keyword_ty k)
3568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3570 VISIT(c, expr, k->value);
3571 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572}
3573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 whether they are true or false.
3576
3577 Return values: 1 for true, 0 for false, -1 for non-constant.
3578 */
3579
3580static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003581expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 char *id;
3584 switch (e->kind) {
3585 case Ellipsis_kind:
3586 return 1;
3587 case Num_kind:
3588 return PyObject_IsTrue(e->v.Num.n);
3589 case Str_kind:
3590 return PyObject_IsTrue(e->v.Str.s);
3591 case Name_kind:
3592 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003593 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003594 if (id && strcmp(id, "__debug__") == 0)
3595 return !c->c_optimize;
3596 return -1;
3597 case NameConstant_kind: {
3598 PyObject *o = e->v.NameConstant.value;
3599 if (o == Py_None)
3600 return 0;
3601 else if (o == Py_True)
3602 return 1;
3603 else if (o == Py_False)
3604 return 0;
3605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 default:
3607 return -1;
3608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609}
3610
Yury Selivanov75445082015-05-11 22:57:16 -04003611
3612/*
3613 Implements the async with statement.
3614
3615 The semantics outlined in that PEP are as follows:
3616
3617 async with EXPR as VAR:
3618 BLOCK
3619
3620 It is implemented roughly as:
3621
3622 context = EXPR
3623 exit = context.__aexit__ # not calling it
3624 value = await context.__aenter__()
3625 try:
3626 VAR = value # if VAR present in the syntax
3627 BLOCK
3628 finally:
3629 if an exception was raised:
3630 exc = copy of (exception, instance, traceback)
3631 else:
3632 exc = (None, None, None)
3633 if not (await exit(*exc)):
3634 raise
3635 */
3636static int
3637compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3638{
3639 basicblock *block, *finally;
3640 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3641
3642 assert(s->kind == AsyncWith_kind);
3643
3644 block = compiler_new_block(c);
3645 finally = compiler_new_block(c);
3646 if (!block || !finally)
3647 return 0;
3648
3649 /* Evaluate EXPR */
3650 VISIT(c, expr, item->context_expr);
3651
3652 ADDOP(c, BEFORE_ASYNC_WITH);
3653 ADDOP(c, GET_AWAITABLE);
3654 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3655 ADDOP(c, YIELD_FROM);
3656
3657 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3658
3659 /* SETUP_ASYNC_WITH pushes a finally block. */
3660 compiler_use_next_block(c, block);
3661 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3662 return 0;
3663 }
3664
3665 if (item->optional_vars) {
3666 VISIT(c, expr, item->optional_vars);
3667 }
3668 else {
3669 /* Discard result from context.__aenter__() */
3670 ADDOP(c, POP_TOP);
3671 }
3672
3673 pos++;
3674 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3675 /* BLOCK code */
3676 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3677 else if (!compiler_async_with(c, s, pos))
3678 return 0;
3679
3680 /* End of try block; start the finally block */
3681 ADDOP(c, POP_BLOCK);
3682 compiler_pop_fblock(c, FINALLY_TRY, block);
3683
3684 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3685 compiler_use_next_block(c, finally);
3686 if (!compiler_push_fblock(c, FINALLY_END, finally))
3687 return 0;
3688
3689 /* Finally block starts; context.__exit__ is on the stack under
3690 the exception or return information. Just issue our magic
3691 opcode. */
3692 ADDOP(c, WITH_CLEANUP_START);
3693
3694 ADDOP(c, GET_AWAITABLE);
3695 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3696 ADDOP(c, YIELD_FROM);
3697
3698 ADDOP(c, WITH_CLEANUP_FINISH);
3699
3700 /* Finally block ends. */
3701 ADDOP(c, END_FINALLY);
3702 compiler_pop_fblock(c, FINALLY_END, finally);
3703 return 1;
3704}
3705
3706
Guido van Rossumc2e20742006-02-27 22:32:47 +00003707/*
3708 Implements the with statement from PEP 343.
3709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003711
3712 with EXPR as VAR:
3713 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714
Guido van Rossumc2e20742006-02-27 22:32:47 +00003715 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716
Thomas Wouters477c8d52006-05-27 19:21:47 +00003717 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003718 exit = context.__exit__ # not calling it
3719 value = context.__enter__()
3720 try:
3721 VAR = value # if VAR present in the syntax
3722 BLOCK
3723 finally:
3724 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003725 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003726 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003727 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003728 exit(*exc)
3729 */
3730static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003731compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003732{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003733 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003734 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003735
3736 assert(s->kind == With_kind);
3737
Guido van Rossumc2e20742006-02-27 22:32:47 +00003738 block = compiler_new_block(c);
3739 finally = compiler_new_block(c);
3740 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003741 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003742
Thomas Wouters477c8d52006-05-27 19:21:47 +00003743 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003744 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003745 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003746
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003747 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003748 compiler_use_next_block(c, block);
3749 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003750 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003751 }
3752
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003753 if (item->optional_vars) {
3754 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003755 }
3756 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003758 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003759 }
3760
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003761 pos++;
3762 if (pos == asdl_seq_LEN(s->v.With.items))
3763 /* BLOCK code */
3764 VISIT_SEQ(c, stmt, s->v.With.body)
3765 else if (!compiler_with(c, s, pos))
3766 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003767
3768 /* End of try block; start the finally block */
3769 ADDOP(c, POP_BLOCK);
3770 compiler_pop_fblock(c, FINALLY_TRY, block);
3771
3772 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3773 compiler_use_next_block(c, finally);
3774 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003775 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003776
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003777 /* Finally block starts; context.__exit__ is on the stack under
3778 the exception or return information. Just issue our magic
3779 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003780 ADDOP(c, WITH_CLEANUP_START);
3781 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003782
3783 /* Finally block ends. */
3784 ADDOP(c, END_FINALLY);
3785 compiler_pop_fblock(c, FINALLY_END, finally);
3786 return 1;
3787}
3788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789static int
3790compiler_visit_expr(struct compiler *c, expr_ty e)
3791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 /* If expr e has a different line number than the last expr/stmt,
3793 set a new line number for the next instruction.
3794 */
3795 if (e->lineno > c->u->u_lineno) {
3796 c->u->u_lineno = e->lineno;
3797 c->u->u_lineno_set = 0;
3798 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003799 /* Updating the column offset is always harmless. */
3800 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 switch (e->kind) {
3802 case BoolOp_kind:
3803 return compiler_boolop(c, e);
3804 case BinOp_kind:
3805 VISIT(c, expr, e->v.BinOp.left);
3806 VISIT(c, expr, e->v.BinOp.right);
3807 ADDOP(c, binop(c, e->v.BinOp.op));
3808 break;
3809 case UnaryOp_kind:
3810 VISIT(c, expr, e->v.UnaryOp.operand);
3811 ADDOP(c, unaryop(e->v.UnaryOp.op));
3812 break;
3813 case Lambda_kind:
3814 return compiler_lambda(c, e);
3815 case IfExp_kind:
3816 return compiler_ifexp(c, e);
3817 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003820 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 case GeneratorExp_kind:
3822 return compiler_genexp(c, e);
3823 case ListComp_kind:
3824 return compiler_listcomp(c, e);
3825 case SetComp_kind:
3826 return compiler_setcomp(c, e);
3827 case DictComp_kind:
3828 return compiler_dictcomp(c, e);
3829 case Yield_kind:
3830 if (c->u->u_ste->ste_type != FunctionBlock)
3831 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003832 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3833 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003834 if (e->v.Yield.value) {
3835 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 }
3837 else {
3838 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3839 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003840 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003842 case YieldFrom_kind:
3843 if (c->u->u_ste->ste_type != FunctionBlock)
3844 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003845
3846 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3847 return compiler_error(c, "'yield from' inside async function");
3848
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003849 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003850 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003851 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3852 ADDOP(c, YIELD_FROM);
3853 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003854 case Await_kind:
3855 if (c->u->u_ste->ste_type != FunctionBlock)
3856 return compiler_error(c, "'await' outside function");
3857
Yury Selivanov9dec0352015-06-30 12:49:04 -04003858 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3859 return compiler_error(
3860 c, "'await' expressions in comprehensions are not supported");
3861
Yury Selivanov75445082015-05-11 22:57:16 -04003862 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