blob: 3a49ecec281b5c0dfbf1b91f0e6cdd5bcc0681da [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
46 unsigned i_hasarg : 1;
47 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinnerad9a0662013-11-19 22:23:20 +0100199static int compiler_call_helper(struct compiler *c, Py_ssize_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static PyCodeObject *assemble(struct compiler *, int addNone);
206static PyObject *__doc__;
207
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400208#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* Name mangling: __private becomes _classname__private.
214 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200215 PyObject *result;
216 size_t nlen, plen, ipriv;
217 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 PyUnicode_READ_CHAR(ident, 0) != '_' ||
220 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_INCREF(ident);
222 return ident;
223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 nlen = PyUnicode_GET_LENGTH(ident);
225 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 The only time a name with a dot can occur is when
229 we are compiling an import statement that has a
230 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 TODO(jhylton): Decide whether we want to support
233 mangling of the module name, e.g. __M.X.
234 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
236 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
237 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident; /* Don't mangle __whatever__ */
240 }
241 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 ipriv = 0;
243 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
244 ipriv++;
245 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle if class is just underscores */
248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000250
Antoine Pitrou55bff892013-04-06 21:21:04 +0200251 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
252 PyErr_SetString(PyExc_OverflowError,
253 "private identifier too large to be mangled");
254 return NULL;
255 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
258 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
259 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
260
261 result = PyUnicode_New(1 + nlen + plen, maxchar);
262 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
265 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200266 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
267 Py_DECREF(result);
268 return NULL;
269 }
270 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
271 Py_DECREF(result);
272 return NULL;
273 }
Victor Stinner8f825062012-04-27 13:55:39 +0200274 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000276}
277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278static int
279compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 c->c_stack = PyList_New(0);
284 if (!c->c_stack)
285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288}
289
290PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200291PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
292 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct compiler c;
295 PyCodeObject *co = NULL;
296 PyCompilerFlags local_flags;
297 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!__doc__) {
300 __doc__ = PyUnicode_InternFromString("__doc__");
301 if (!__doc__)
302 return NULL;
303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!compiler_init(&c))
306 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200307 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 c.c_filename = filename;
309 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200310 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (c.c_future == NULL)
312 goto finally;
313 if (!flags) {
314 local_flags.cf_flags = 0;
315 flags = &local_flags;
316 }
317 merged = c.c_future->ff_features | flags->cf_flags;
318 c.c_future->ff_features = merged;
319 flags->cf_flags = merged;
320 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000321 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Victor Stinner14e461d2013-08-26 22:28:21 +0200324 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (c.c_st == NULL) {
326 if (!PyErr_Occurred())
327 PyErr_SetString(PyExc_SystemError, "no symtable");
328 goto finally;
329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Thomas Wouters1175c432006-02-27 22:49:54 +0000333 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 compiler_free(&c);
335 assert(co || PyErr_Occurred());
336 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337}
338
339PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200340PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
341 int optimize, PyArena *arena)
342{
343 PyObject *filename;
344 PyCodeObject *co;
345 filename = PyUnicode_DecodeFSDefault(filename_str);
346 if (filename == NULL)
347 return NULL;
348 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
349 Py_DECREF(filename);
350 return co;
351
352}
353
354PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355PyNode_Compile(struct _node *n, const char *filename)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyCodeObject *co = NULL;
358 mod_ty mod;
359 PyArena *arena = PyArena_New();
360 if (!arena)
361 return NULL;
362 mod = PyAST_FromNode(n, NULL, filename, arena);
363 if (mod)
364 co = PyAST_Compile(mod, filename, NULL, arena);
365 PyArena_Free(arena);
366 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000367}
368
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000369static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (c->c_st)
373 PySymtable_Free(c->c_st);
374 if (c->c_future)
375 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200376 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000378}
379
Guido van Rossum79f25d91997-04-29 20:08:16 +0000380static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t i, n;
384 PyObject *v, *k;
385 PyObject *dict = PyDict_New();
386 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 n = PyList_Size(list);
389 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100390 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!v) {
392 Py_DECREF(dict);
393 return NULL;
394 }
395 k = PyList_GET_ITEM(list, i);
396 k = PyTuple_Pack(2, k, k->ob_type);
397 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
398 Py_XDECREF(k);
399 Py_DECREF(v);
400 Py_DECREF(dict);
401 return NULL;
402 }
403 Py_DECREF(k);
404 Py_DECREF(v);
405 }
406 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407}
408
409/* Return new dict containing names from src that match scope(s).
410
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000413values are integers, starting at offset and increasing by one for
414each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415*/
416
417static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100418dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700420 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500422 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 assert(offset >= 0);
425 if (dest == NULL)
426 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Meador Inge2ca63152012-07-18 14:20:11 -0500428 /* Sort the keys so that we have a deterministic order on the indexes
429 saved in the returned dictionary. These indexes are used as indexes
430 into the free and cell var storage. Therefore if they aren't
431 deterministic, then the generated bytecode is not deterministic.
432 */
433 sorted_keys = PyDict_Keys(src);
434 if (sorted_keys == NULL)
435 return NULL;
436 if (PyList_Sort(sorted_keys) != 0) {
437 Py_DECREF(sorted_keys);
438 return NULL;
439 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500440 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500441
442 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* XXX this should probably be a macro in symtable.h */
444 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500445 k = PyList_GET_ITEM(sorted_keys, key_i);
446 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 assert(PyLong_Check(v));
448 vi = PyLong_AS_LONG(v);
449 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100452 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500454 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(dest);
456 return NULL;
457 }
458 i++;
459 tuple = PyTuple_Pack(2, k, k->ob_type);
460 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500461 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 Py_DECREF(item);
463 Py_DECREF(dest);
464 Py_XDECREF(tuple);
465 return NULL;
466 }
467 Py_DECREF(item);
468 Py_DECREF(tuple);
469 }
470 }
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000473}
474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475static void
476compiler_unit_check(struct compiler_unit *u)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 basicblock *block;
479 for (block = u->u_blocks; block != NULL; block = block->b_list) {
480 assert((void *)block != (void *)0xcbcbcbcb);
481 assert((void *)block != (void *)0xfbfbfbfb);
482 assert((void *)block != (void *)0xdbdbdbdb);
483 if (block->b_instr != NULL) {
484 assert(block->b_ialloc > 0);
485 assert(block->b_iused > 0);
486 assert(block->b_ialloc >= block->b_iused);
487 }
488 else {
489 assert (block->b_iused == 0);
490 assert (block->b_ialloc == 0);
491 }
492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493}
494
495static void
496compiler_unit_free(struct compiler_unit *u)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 compiler_unit_check(u);
501 b = u->u_blocks;
502 while (b != NULL) {
503 if (b->b_instr)
504 PyObject_Free((void *)b->b_instr);
505 next = b->b_list;
506 PyObject_Free((void *)b);
507 b = next;
508 }
509 Py_CLEAR(u->u_ste);
510 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400511 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_CLEAR(u->u_consts);
513 Py_CLEAR(u->u_names);
514 Py_CLEAR(u->u_varnames);
515 Py_CLEAR(u->u_freevars);
516 Py_CLEAR(u->u_cellvars);
517 Py_CLEAR(u->u_private);
518 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519}
520
521static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100522compiler_enter_scope(struct compiler *c, identifier name,
523 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
551 /* Cook up a implicit __class__ cell. */
552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
562 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
623 if (compiler_use_new_block(c) == NULL)
624 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400626 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
627 if (!compiler_set_qualname(c))
628 return 0;
629 }
630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632}
633
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000634static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635compiler_exit_scope(struct compiler *c)
636{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100637 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 c->c_nestlevel--;
641 compiler_unit_free(c->u);
642 /* Restore c->u to the parent unit. */
643 n = PyList_GET_SIZE(c->c_stack) - 1;
644 if (n >= 0) {
645 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400646 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 assert(c->u);
648 /* we are deleting from a list so this really shouldn't fail */
649 if (PySequence_DelItem(c->c_stack, n) < 0)
650 Py_FatalError("compiler_exit_scope()");
651 compiler_unit_check(c->u);
652 }
653 else
654 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658static int
659compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400662 _Py_static_string(dot_locals, ".<locals>");
663 Py_ssize_t stack_size;
664 struct compiler_unit *u = c->u;
665 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400669 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 if (stack_size > 1) {
671 int scope, force_global = 0;
672 struct compiler_unit *parent;
673 PyObject *mangled, *capsule;
674
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400675 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400676 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 assert(parent);
678
Yury Selivanov75445082015-05-11 22:57:16 -0400679 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
680 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
681 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 assert(u->u_name);
683 mangled = _Py_Mangle(parent->u_private, u->u_name);
684 if (!mangled)
685 return 0;
686 scope = PyST_GetScope(parent->u_ste, mangled);
687 Py_DECREF(mangled);
688 assert(scope != GLOBAL_IMPLICIT);
689 if (scope == GLOBAL_EXPLICIT)
690 force_global = 1;
691 }
692
693 if (!force_global) {
694 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400695 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
697 dot_locals_str = _PyUnicode_FromId(&dot_locals);
698 if (dot_locals_str == NULL)
699 return 0;
700 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
701 if (base == NULL)
702 return 0;
703 }
704 else {
705 Py_INCREF(parent->u_qualname);
706 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100708 }
709 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400711 if (base != NULL) {
712 dot_str = _PyUnicode_FromId(&dot);
713 if (dot_str == NULL) {
714 Py_DECREF(base);
715 return 0;
716 }
717 name = PyUnicode_Concat(base, dot_str);
718 Py_DECREF(base);
719 if (name == NULL)
720 return 0;
721 PyUnicode_Append(&name, u->u_name);
722 if (name == NULL)
723 return 0;
724 }
725 else {
726 Py_INCREF(u->u_name);
727 name = u->u_name;
728 }
729 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100732}
733
Eric V. Smith235a6f02015-09-19 14:51:32 -0400734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735/* Allocate a new block and return a pointer to it.
736 Returns NULL on error.
737*/
738
739static basicblock *
740compiler_new_block(struct compiler *c)
741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 basicblock *b;
743 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 u = c->u;
746 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
747 if (b == NULL) {
748 PyErr_NoMemory();
749 return NULL;
750 }
751 memset((void *)b, 0, sizeof(basicblock));
752 /* Extend the singly linked list of blocks with new block. */
753 b->b_list = u->u_blocks;
754 u->u_blocks = b;
755 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756}
757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758static basicblock *
759compiler_use_new_block(struct compiler *c)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 basicblock *block = compiler_new_block(c);
762 if (block == NULL)
763 return NULL;
764 c->u->u_curblock = block;
765 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766}
767
768static basicblock *
769compiler_next_block(struct compiler *c)
770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 basicblock *block = compiler_new_block(c);
772 if (block == NULL)
773 return NULL;
774 c->u->u_curblock->b_next = block;
775 c->u->u_curblock = block;
776 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777}
778
779static basicblock *
780compiler_use_next_block(struct compiler *c, basicblock *block)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 assert(block != NULL);
783 c->u->u_curblock->b_next = block;
784 c->u->u_curblock = block;
785 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786}
787
788/* Returns the offset of the next instruction in the current block's
789 b_instr array. Resizes the b_instr as necessary.
790 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000791*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792
793static int
794compiler_next_instr(struct compiler *c, basicblock *b)
795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 assert(b != NULL);
797 if (b->b_instr == NULL) {
798 b->b_instr = (struct instr *)PyObject_Malloc(
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 if (b->b_instr == NULL) {
801 PyErr_NoMemory();
802 return -1;
803 }
804 b->b_ialloc = DEFAULT_BLOCK_SIZE;
805 memset((char *)b->b_instr, 0,
806 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
807 }
808 else if (b->b_iused == b->b_ialloc) {
809 struct instr *tmp;
810 size_t oldsize, newsize;
811 oldsize = b->b_ialloc * sizeof(struct instr);
812 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (oldsize > (PY_SIZE_MAX >> 1)) {
815 PyErr_NoMemory();
816 return -1;
817 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (newsize == 0) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_ialloc <<= 1;
824 tmp = (struct instr *)PyObject_Realloc(
825 (void *)b->b_instr, newsize);
826 if (tmp == NULL) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 b->b_instr = tmp;
831 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
832 }
833 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834}
835
Christian Heimes2202f872008-02-06 14:31:34 +0000836/* Set the i_lineno member of the instruction at offset off if the
837 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838 already been set. If it has been set, the call has no effect.
839
Christian Heimes2202f872008-02-06 14:31:34 +0000840 The line number is reset in the following cases:
841 - when entering a new scope
842 - on each statement
843 - on each expression that start a new line
844 - before the "except" clause
845 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000846*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848static void
849compiler_set_lineno(struct compiler *c, int off)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 basicblock *b;
852 if (c->u->u_lineno_set)
853 return;
854 c->u->u_lineno_set = 1;
855 b = c->u->u_curblock;
856 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000857}
858
Larry Hastings3a907972013-11-23 14:49:22 -0800859int
860PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 switch (opcode) {
863 case POP_TOP:
864 return -1;
865 case ROT_TWO:
866 case ROT_THREE:
867 return 0;
868 case DUP_TOP:
869 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000870 case DUP_TOP_TWO:
871 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 case UNARY_POSITIVE:
874 case UNARY_NEGATIVE:
875 case UNARY_NOT:
876 case UNARY_INVERT:
877 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 case SET_ADD:
880 case LIST_APPEND:
881 return -1;
882 case MAP_ADD:
883 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_POWER:
886 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400887 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case BINARY_MODULO:
889 case BINARY_ADD:
890 case BINARY_SUBTRACT:
891 case BINARY_SUBSCR:
892 case BINARY_FLOOR_DIVIDE:
893 case BINARY_TRUE_DIVIDE:
894 return -1;
895 case INPLACE_FLOOR_DIVIDE:
896 case INPLACE_TRUE_DIVIDE:
897 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 case INPLACE_ADD:
900 case INPLACE_SUBTRACT:
901 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400902 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case INPLACE_MODULO:
904 return -1;
905 case STORE_SUBSCR:
906 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case DELETE_SUBSCR:
908 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case BINARY_LSHIFT:
911 case BINARY_RSHIFT:
912 case BINARY_AND:
913 case BINARY_XOR:
914 case BINARY_OR:
915 return -1;
916 case INPLACE_POWER:
917 return -1;
918 case GET_ITER:
919 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case PRINT_EXPR:
922 return -1;
923 case LOAD_BUILD_CLASS:
924 return 1;
925 case INPLACE_LSHIFT:
926 case INPLACE_RSHIFT:
927 case INPLACE_AND:
928 case INPLACE_XOR:
929 case INPLACE_OR:
930 return -1;
931 case BREAK_LOOP:
932 return 0;
933 case SETUP_WITH:
934 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400935 case WITH_CLEANUP_START:
936 return 1;
937 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case RETURN_VALUE:
940 return -1;
941 case IMPORT_STAR:
942 return -1;
943 case YIELD_VALUE:
944 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500945 case YIELD_FROM:
946 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case POP_BLOCK:
948 return 0;
949 case POP_EXCEPT:
950 return 0; /* -3 except if bad bytecode */
951 case END_FINALLY:
952 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 case STORE_NAME:
955 return -1;
956 case DELETE_NAME:
957 return 0;
958 case UNPACK_SEQUENCE:
959 return oparg-1;
960 case UNPACK_EX:
961 return (oparg&0xFF) + (oparg>>8);
962 case FOR_ITER:
963 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case STORE_ATTR:
966 return -2;
967 case DELETE_ATTR:
968 return -1;
969 case STORE_GLOBAL:
970 return -1;
971 case DELETE_GLOBAL:
972 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case LOAD_CONST:
974 return 1;
975 case LOAD_NAME:
976 return 1;
977 case BUILD_TUPLE:
978 case BUILD_LIST:
979 case BUILD_SET:
980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
983 case BUILD_SET_UNPACK:
984 case BUILD_MAP_UNPACK:
985 return 1 - oparg;
986 case BUILD_MAP_UNPACK_WITH_CALL:
987 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case LOAD_ATTR:
991 return 0;
992 case COMPARE_OP:
993 return -1;
994 case IMPORT_NAME:
995 return -1;
996 case IMPORT_FROM:
997 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case JUMP_FORWARD:
1000 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1001 case JUMP_IF_FALSE_OR_POP: /* "" */
1002 case JUMP_ABSOLUTE:
1003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case POP_JUMP_IF_FALSE:
1006 case POP_JUMP_IF_TRUE:
1007 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_GLOBAL:
1010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 case CONTINUE_LOOP:
1013 return 0;
1014 case SETUP_LOOP:
1015 return 0;
1016 case SETUP_EXCEPT:
1017 case SETUP_FINALLY:
1018 return 6; /* can push 3 values for the new exception
1019 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_FAST:
1022 return 1;
1023 case STORE_FAST:
1024 return -1;
1025 case DELETE_FAST:
1026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case RAISE_VARARGS:
1029 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001030#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case CALL_FUNCTION:
1032 return -NARGS(oparg);
1033 case CALL_FUNCTION_VAR:
1034 case CALL_FUNCTION_KW:
1035 return -NARGS(oparg)-1;
1036 case CALL_FUNCTION_VAR_KW:
1037 return -NARGS(oparg)-2;
1038 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001039 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001041 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001042#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case BUILD_SLICE:
1044 if (oparg == 3)
1045 return -2;
1046 else
1047 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case LOAD_CLOSURE:
1050 return 1;
1051 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001052 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return 1;
1054 case STORE_DEREF:
1055 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001056 case DELETE_DEREF:
1057 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001058 case GET_AWAITABLE:
1059 return 0;
1060 case SETUP_ASYNC_WITH:
1061 return 6;
1062 case BEFORE_ASYNC_WITH:
1063 return 1;
1064 case GET_AITER:
1065 return 0;
1066 case GET_ANEXT:
1067 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001068 case GET_YIELD_FROM_ITER:
1069 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001071 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 }
Larry Hastings3a907972013-11-23 14:49:22 -08001073 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074}
1075
1076/* Add an opcode with no argument.
1077 Returns 0 on failure, 1 on success.
1078*/
1079
1080static int
1081compiler_addop(struct compiler *c, int opcode)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 basicblock *b;
1084 struct instr *i;
1085 int off;
1086 off = compiler_next_instr(c, c->u->u_curblock);
1087 if (off < 0)
1088 return 0;
1089 b = c->u->u_curblock;
1090 i = &b->b_instr[off];
1091 i->i_opcode = opcode;
1092 i->i_hasarg = 0;
1093 if (opcode == RETURN_VALUE)
1094 b->b_return = 1;
1095 compiler_set_lineno(c, off);
1096 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097}
1098
Victor Stinnerf8e32212013-11-19 23:56:34 +01001099static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001100compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyObject *t, *v;
1103 Py_ssize_t arg;
1104 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105
Serhiy Storchaka95949422013-08-27 19:40:23 +03001106 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1108 if (PyFloat_Check(o)) {
1109 d = PyFloat_AS_DOUBLE(o);
1110 /* all we need is to make the tuple different in either the 0.0
1111 * or -0.0 case from all others, just to avoid the "coercion".
1112 */
1113 if (d == 0.0 && copysign(1.0, d) < 0.0)
1114 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1115 else
1116 t = PyTuple_Pack(2, o, o->ob_type);
1117 }
1118 else if (PyComplex_Check(o)) {
1119 Py_complex z;
1120 int real_negzero, imag_negzero;
1121 /* For the complex case we must make complex(x, 0.)
1122 different from complex(x, -0.) and complex(0., y)
1123 different from complex(-0., y), for any x and y.
1124 All four complex zeros must be distinguished.*/
1125 z = PyComplex_AsCComplex(o);
1126 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1127 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1128 if (real_negzero && imag_negzero) {
1129 t = PyTuple_Pack(5, o, o->ob_type,
1130 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 else if (imag_negzero) {
1133 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 else if (real_negzero) {
1136 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1137 }
1138 else {
1139 t = PyTuple_Pack(2, o, o->ob_type);
1140 }
1141 }
1142 else {
1143 t = PyTuple_Pack(2, o, o->ob_type);
1144 }
1145 if (t == NULL)
1146 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 v = PyDict_GetItem(dict, t);
1149 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001150 if (PyErr_Occurred()) {
1151 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001153 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001155 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (!v) {
1157 Py_DECREF(t);
1158 return -1;
1159 }
1160 if (PyDict_SetItem(dict, t, v) < 0) {
1161 Py_DECREF(t);
1162 Py_DECREF(v);
1163 return -1;
1164 }
1165 Py_DECREF(v);
1166 }
1167 else
1168 arg = PyLong_AsLong(v);
1169 Py_DECREF(t);
1170 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171}
1172
1173static int
1174compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001179 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180 return compiler_addop_i(c, opcode, arg);
1181}
1182
1183static int
1184compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1189 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001190 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191 arg = compiler_add_o(c, dict, mangled);
1192 Py_DECREF(mangled);
1193 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001194 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 return compiler_addop_i(c, opcode, arg);
1196}
1197
1198/* Add an opcode with an integer argument.
1199 Returns 0 on failure, 1 on success.
1200*/
1201
1202static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001203compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 struct instr *i;
1206 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001207
1208 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1209 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001210 assert((-2147483647-1) <= oparg);
1211 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 off = compiler_next_instr(c, c->u->u_curblock);
1214 if (off < 0)
1215 return 0;
1216 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001217 i->i_opcode = opcode;
1218 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 i->i_hasarg = 1;
1220 compiler_set_lineno(c, off);
1221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222}
1223
1224static int
1225compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 struct instr *i;
1228 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 assert(b != NULL);
1231 off = compiler_next_instr(c, c->u->u_curblock);
1232 if (off < 0)
1233 return 0;
1234 i = &c->u->u_curblock->b_instr[off];
1235 i->i_opcode = opcode;
1236 i->i_target = b;
1237 i->i_hasarg = 1;
1238 if (absolute)
1239 i->i_jabs = 1;
1240 else
1241 i->i_jrel = 1;
1242 compiler_set_lineno(c, off);
1243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1247 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248 it as the current block. NEXT_BLOCK() also creates an implicit jump
1249 from the current block to the new block.
1250*/
1251
Thomas Wouters89f507f2006-12-13 04:49:30 +00001252/* The returns inside these macros make it impossible to decref objects
1253 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254*/
1255
1256
1257#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (compiler_use_new_block((C)) == NULL) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (compiler_next_block((C)) == NULL) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop((C), (OP))) \
1269 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001272#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_addop((C), (OP))) { \
1274 compiler_exit_scope(c); \
1275 return 0; \
1276 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001277}
1278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
1284#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_addop_i((C), (OP), (O))) \
1291 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292}
1293
1294#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!compiler_addop_j((C), (OP), (O), 1)) \
1296 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
1299#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (!compiler_addop_j((C), (OP), (O), 0)) \
1301 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302}
1303
1304/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1305 the ASDL name to synthesize the name of the C type and the visit function.
1306*/
1307
1308#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (!compiler_visit_ ## TYPE((C), (V))) \
1310 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001313#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (!compiler_visit_ ## TYPE((C), (V))) { \
1315 compiler_exit_scope(c); \
1316 return 0; \
1317 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001318}
1319
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!compiler_visit_slice((C), (V), (CTX))) \
1322 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323}
1324
1325#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 int _i; \
1327 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1328 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1329 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1330 if (!compiler_visit_ ## TYPE((C), elt)) \
1331 return 0; \
1332 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333}
1334
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001335#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 int _i; \
1337 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1338 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1339 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1340 if (!compiler_visit_ ## TYPE((C), elt)) { \
1341 compiler_exit_scope(c); \
1342 return 0; \
1343 } \
1344 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001345}
1346
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347static int
1348compiler_isdocstring(stmt_ty s)
1349{
1350 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001351 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352 return s->v.Expr.value->kind == Str_kind;
1353}
1354
1355/* Compile a sequence of statements, checking for a docstring. */
1356
1357static int
1358compiler_body(struct compiler *c, asdl_seq *stmts)
1359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 int i = 0;
1361 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 if (!asdl_seq_LEN(stmts))
1364 return 1;
1365 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001366 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* don't generate docstrings if -OO */
1368 i = 1;
1369 VISIT(c, expr, st->v.Expr.value);
1370 if (!compiler_nameop(c, __doc__, Store))
1371 return 0;
1372 }
1373 for (; i < asdl_seq_LEN(stmts); i++)
1374 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1375 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376}
1377
1378static PyCodeObject *
1379compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 PyCodeObject *co;
1382 int addNone = 1;
1383 static PyObject *module;
1384 if (!module) {
1385 module = PyUnicode_InternFromString("<module>");
1386 if (!module)
1387 return NULL;
1388 }
1389 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001390 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 return NULL;
1392 switch (mod->kind) {
1393 case Module_kind:
1394 if (!compiler_body(c, mod->v.Module.body)) {
1395 compiler_exit_scope(c);
1396 return 0;
1397 }
1398 break;
1399 case Interactive_kind:
1400 c->c_interactive = 1;
1401 VISIT_SEQ_IN_SCOPE(c, stmt,
1402 mod->v.Interactive.body);
1403 break;
1404 case Expression_kind:
1405 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1406 addNone = 0;
1407 break;
1408 case Suite_kind:
1409 PyErr_SetString(PyExc_SystemError,
1410 "suite should not be possible");
1411 return 0;
1412 default:
1413 PyErr_Format(PyExc_SystemError,
1414 "module kind %d should not be possible",
1415 mod->kind);
1416 return 0;
1417 }
1418 co = assemble(c, addNone);
1419 compiler_exit_scope(c);
1420 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001421}
1422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423/* The test for LOCAL must come before the test for FREE in order to
1424 handle classes where name is both local and free. The local var is
1425 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001426*/
1427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428static int
1429get_ref_type(struct compiler *c, PyObject *name)
1430{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001431 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001432 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1433 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1434 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001435 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (scope == 0) {
1437 char buf[350];
1438 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001439 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001441 PyUnicode_AsUTF8(name),
1442 PyUnicode_AsUTF8(c->u->u_name),
1443 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1444 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1445 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1446 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 );
1448 Py_FatalError(buf);
1449 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452}
1453
1454static int
1455compiler_lookup_arg(PyObject *dict, PyObject *name)
1456{
1457 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001460 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001462 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001464 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001465 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466}
1467
1468static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001469compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001471 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001472 if (qualname == NULL)
1473 qualname = co->co_name;
1474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (free == 0) {
1476 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001477 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 ADDOP_I(c, MAKE_FUNCTION, args);
1479 return 1;
1480 }
1481 for (i = 0; i < free; ++i) {
1482 /* Bypass com_addop_varname because it will generate
1483 LOAD_DEREF but LOAD_CLOSURE is needed.
1484 */
1485 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1486 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 /* Special case: If a class contains a method with a
1489 free variable that has the same name as a method,
1490 the name will be considered free *and* local in the
1491 class. It should be handled by the closure, as
1492 well as by the normal name loookup logic.
1493 */
1494 reftype = get_ref_type(c, name);
1495 if (reftype == CELL)
1496 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1497 else /* (reftype == FREE) */
1498 arg = compiler_lookup_arg(c->u->u_freevars, name);
1499 if (arg == -1) {
1500 fprintf(stderr,
1501 "lookup %s in %s %d %d\n"
1502 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001503 PyUnicode_AsUTF8(PyObject_Repr(name)),
1504 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001506 PyUnicode_AsUTF8(co->co_name),
1507 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 Py_FatalError("compiler_make_closure()");
1509 }
1510 ADDOP_I(c, LOAD_CLOSURE, arg);
1511 }
1512 ADDOP_I(c, BUILD_TUPLE, free);
1513 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001514 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 ADDOP_I(c, MAKE_CLOSURE, args);
1516 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517}
1518
1519static int
1520compiler_decorators(struct compiler *c, asdl_seq* decos)
1521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (!decos)
1525 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1528 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1529 }
1530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531}
1532
1533static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001534compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int i, default_count = 0;
1538 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1539 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1540 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1541 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001542 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1543 if (!mangled)
1544 return -1;
1545 ADDOP_O(c, LOAD_CONST, mangled, consts);
1546 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (!compiler_visit_expr(c, default_)) {
1548 return -1;
1549 }
1550 default_count++;
1551 }
1552 }
1553 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001554}
1555
1556static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001557compiler_visit_argannotation(struct compiler *c, identifier id,
1558 expr_ty annotation, PyObject *names)
1559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001561 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001563 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001564 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001565 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001566 if (PyList_Append(names, mangled) < 0) {
1567 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001568 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001569 }
1570 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001572 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001573}
1574
1575static int
1576compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1577 PyObject *names)
1578{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001579 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 for (i = 0; i < asdl_seq_LEN(args); i++) {
1581 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001582 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 c,
1584 arg->arg,
1585 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001586 names))
1587 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001589 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001590}
1591
1592static int
1593compiler_visit_annotations(struct compiler *c, arguments_ty args,
1594 expr_ty returns)
1595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 /* Push arg annotations and a list of the argument names. Return the #
1597 of items pushed. The expressions are evaluated out-of-order wrt the
1598 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1601 */
1602 static identifier return_str;
1603 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001604 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 names = PyList_New(0);
1606 if (!names)
1607 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001608
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001609 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001611 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001612 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001613 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001615 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001617 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001618 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001619 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (!return_str) {
1623 return_str = PyUnicode_InternFromString("return");
1624 if (!return_str)
1625 goto error;
1626 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001627 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 goto error;
1629 }
1630
1631 len = PyList_GET_SIZE(names);
1632 if (len > 65534) {
1633 /* len must fit in 16 bits, and len is incremented below */
1634 PyErr_SetString(PyExc_SyntaxError,
1635 "too many annotations");
1636 goto error;
1637 }
1638 if (len) {
1639 /* convert names to a tuple and place on stack */
1640 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001641 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyObject *s = PyTuple_New(len);
1643 if (!s)
1644 goto error;
1645 for (i = 0; i < len; i++) {
1646 elt = PyList_GET_ITEM(names, i);
1647 Py_INCREF(elt);
1648 PyTuple_SET_ITEM(s, i, elt);
1649 }
1650 ADDOP_O(c, LOAD_CONST, s, consts);
1651 Py_DECREF(s);
1652 len++; /* include the just-pushed tuple */
1653 }
1654 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001655
1656 /* We just checked that len <= 65535, see above */
1657 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001658
1659error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 Py_DECREF(names);
1661 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001662}
1663
1664static int
Yury Selivanov75445082015-05-11 22:57:16 -04001665compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001668 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001669 arguments_ty args;
1670 expr_ty returns;
1671 identifier name;
1672 asdl_seq* decos;
1673 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001675 Py_ssize_t i, n, arglength;
1676 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001678 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679
Yury Selivanov75445082015-05-11 22:57:16 -04001680
1681 if (is_async) {
1682 assert(s->kind == AsyncFunctionDef_kind);
1683
1684 args = s->v.AsyncFunctionDef.args;
1685 returns = s->v.AsyncFunctionDef.returns;
1686 decos = s->v.AsyncFunctionDef.decorator_list;
1687 name = s->v.AsyncFunctionDef.name;
1688 body = s->v.AsyncFunctionDef.body;
1689
1690 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1691 } else {
1692 assert(s->kind == FunctionDef_kind);
1693
1694 args = s->v.FunctionDef.args;
1695 returns = s->v.FunctionDef.returns;
1696 decos = s->v.FunctionDef.decorator_list;
1697 name = s->v.FunctionDef.name;
1698 body = s->v.FunctionDef.body;
1699
1700 scope_type = COMPILER_SCOPE_FUNCTION;
1701 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (!compiler_decorators(c, decos))
1704 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001705 if (args->defaults)
1706 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (args->kwonlyargs) {
1708 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1709 args->kw_defaults);
1710 if (res < 0)
1711 return 0;
1712 kw_default_count = res;
1713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 num_annotations = compiler_visit_annotations(c, args, returns);
1715 if (num_annotations < 0)
1716 return 0;
1717 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001718
Yury Selivanov75445082015-05-11 22:57:16 -04001719 if (!compiler_enter_scope(c, name,
1720 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 s->lineno))
1722 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723
Yury Selivanov75445082015-05-11 22:57:16 -04001724 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001726 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 first_const = st->v.Expr.value->v.Str.s;
1728 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1729 compiler_exit_scope(c);
1730 return 0;
1731 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 c->u->u_argcount = asdl_seq_LEN(args->args);
1734 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001735 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* if there was a docstring, we need to skip the first statement */
1737 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001738 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 VISIT_IN_SCOPE(c, stmt, st);
1740 }
1741 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001742 qualname = c->u->u_qualname;
1743 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001745 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001746 Py_XDECREF(qualname);
1747 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001749 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 arglength = asdl_seq_LEN(args->defaults);
1752 arglength |= kw_default_count << 8;
1753 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001754 if (is_async)
1755 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001756 compiler_make_closure(c, co, arglength, qualname);
1757 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* decorators */
1761 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1762 ADDOP_I(c, CALL_FUNCTION, 1);
1763 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764
Yury Selivanov75445082015-05-11 22:57:16 -04001765 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766}
1767
1768static int
1769compiler_class(struct compiler *c, stmt_ty s)
1770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyCodeObject *co;
1772 PyObject *str;
1773 int i;
1774 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (!compiler_decorators(c, decos))
1777 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 /* ultimately generate code for:
1780 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1781 where:
1782 <func> is a function/closure created from the class body;
1783 it has a single argument (__locals__) where the dict
1784 (or MutableSequence) representing the locals is passed
1785 <name> is the class name
1786 <bases> is the positional arguments and *varargs argument
1787 <keywords> is the keyword arguments and **kwds argument
1788 This borrows from compiler_call.
1789 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001792 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1793 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return 0;
1795 /* this block represents what we do in the new scope */
1796 {
1797 /* use the class name for name mangling */
1798 Py_INCREF(s->v.ClassDef.name);
1799 Py_XDECREF(c->u->u_private);
1800 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* load (global) __name__ ... */
1802 str = PyUnicode_InternFromString("__name__");
1803 if (!str || !compiler_nameop(c, str, Load)) {
1804 Py_XDECREF(str);
1805 compiler_exit_scope(c);
1806 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 Py_DECREF(str);
1809 /* ... and store it as __module__ */
1810 str = PyUnicode_InternFromString("__module__");
1811 if (!str || !compiler_nameop(c, str, Store)) {
1812 Py_XDECREF(str);
1813 compiler_exit_scope(c);
1814 return 0;
1815 }
1816 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001817 assert(c->u->u_qualname);
1818 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001819 str = PyUnicode_InternFromString("__qualname__");
1820 if (!str || !compiler_nameop(c, str, Store)) {
1821 Py_XDECREF(str);
1822 compiler_exit_scope(c);
1823 return 0;
1824 }
1825 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 /* compile the body proper */
1827 if (!compiler_body(c, s->v.ClassDef.body)) {
1828 compiler_exit_scope(c);
1829 return 0;
1830 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001831 if (c->u->u_ste->ste_needs_class_closure) {
1832 /* return the (empty) __class__ cell */
1833 str = PyUnicode_InternFromString("__class__");
1834 if (str == NULL) {
1835 compiler_exit_scope(c);
1836 return 0;
1837 }
1838 i = compiler_lookup_arg(c->u->u_cellvars, str);
1839 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001840 if (i < 0) {
1841 compiler_exit_scope(c);
1842 return 0;
1843 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001844 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 /* Return the cell where to store __class__ */
1846 ADDOP_I(c, LOAD_CLOSURE, i);
1847 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001848 else {
1849 assert(PyDict_Size(c->u->u_cellvars) == 0);
1850 /* This happens when nobody references the cell. Return None. */
1851 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1854 /* create the code object */
1855 co = assemble(c, 1);
1856 }
1857 /* leave the new scope */
1858 compiler_exit_scope(c);
1859 if (co == NULL)
1860 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 /* 2. load the 'build_class' function */
1863 ADDOP(c, LOAD_BUILD_CLASS);
1864
1865 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001866 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 Py_DECREF(co);
1868
1869 /* 4. load class name */
1870 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1871
1872 /* 5. generate the rest of the code for the call */
1873 if (!compiler_call_helper(c, 2,
1874 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001875 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 return 0;
1877
1878 /* 6. apply decorators */
1879 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1880 ADDOP_I(c, CALL_FUNCTION, 1);
1881 }
1882
1883 /* 7. store into <name> */
1884 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1885 return 0;
1886 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887}
1888
1889static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001890compiler_ifexp(struct compiler *c, expr_ty e)
1891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 basicblock *end, *next;
1893
1894 assert(e->kind == IfExp_kind);
1895 end = compiler_new_block(c);
1896 if (end == NULL)
1897 return 0;
1898 next = compiler_new_block(c);
1899 if (next == NULL)
1900 return 0;
1901 VISIT(c, expr, e->v.IfExp.test);
1902 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1903 VISIT(c, expr, e->v.IfExp.body);
1904 ADDOP_JREL(c, JUMP_FORWARD, end);
1905 compiler_use_next_block(c, next);
1906 VISIT(c, expr, e->v.IfExp.orelse);
1907 compiler_use_next_block(c, end);
1908 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001909}
1910
1911static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912compiler_lambda(struct compiler *c, expr_ty e)
1913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001915 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001917 int kw_default_count = 0;
1918 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 arguments_ty args = e->v.Lambda.args;
1920 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (!name) {
1923 name = PyUnicode_InternFromString("<lambda>");
1924 if (!name)
1925 return 0;
1926 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001928 if (args->defaults)
1929 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (args->kwonlyargs) {
1931 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1932 args->kw_defaults);
1933 if (res < 0) return 0;
1934 kw_default_count = res;
1935 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001936 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001937 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* Make None the first constant, so the lambda can't have a
1941 docstring. */
1942 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1943 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 c->u->u_argcount = asdl_seq_LEN(args->args);
1946 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1947 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1948 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001949 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
1951 else {
1952 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001953 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001955 qualname = c->u->u_qualname;
1956 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001958 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 arglength = asdl_seq_LEN(args->defaults);
1962 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001963 compiler_make_closure(c, co, arglength, qualname);
1964 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 Py_DECREF(co);
1966
1967 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968}
1969
1970static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971compiler_if(struct compiler *c, stmt_ty s)
1972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 basicblock *end, *next;
1974 int constant;
1975 assert(s->kind == If_kind);
1976 end = compiler_new_block(c);
1977 if (end == NULL)
1978 return 0;
1979
Georg Brandl8334fd92010-12-04 10:26:46 +00001980 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* constant = 0: "if 0"
1982 * constant = 1: "if 1", "if 2", ...
1983 * constant = -1: rest */
1984 if (constant == 0) {
1985 if (s->v.If.orelse)
1986 VISIT_SEQ(c, stmt, s->v.If.orelse);
1987 } else if (constant == 1) {
1988 VISIT_SEQ(c, stmt, s->v.If.body);
1989 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001990 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 next = compiler_new_block(c);
1992 if (next == NULL)
1993 return 0;
1994 }
1995 else
1996 next = end;
1997 VISIT(c, expr, s->v.If.test);
1998 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1999 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002000 if (asdl_seq_LEN(s->v.If.orelse)) {
2001 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 compiler_use_next_block(c, next);
2003 VISIT_SEQ(c, stmt, s->v.If.orelse);
2004 }
2005 }
2006 compiler_use_next_block(c, end);
2007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008}
2009
2010static int
2011compiler_for(struct compiler *c, stmt_ty s)
2012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 start = compiler_new_block(c);
2016 cleanup = compiler_new_block(c);
2017 end = compiler_new_block(c);
2018 if (start == NULL || end == NULL || cleanup == NULL)
2019 return 0;
2020 ADDOP_JREL(c, SETUP_LOOP, end);
2021 if (!compiler_push_fblock(c, LOOP, start))
2022 return 0;
2023 VISIT(c, expr, s->v.For.iter);
2024 ADDOP(c, GET_ITER);
2025 compiler_use_next_block(c, start);
2026 ADDOP_JREL(c, FOR_ITER, cleanup);
2027 VISIT(c, expr, s->v.For.target);
2028 VISIT_SEQ(c, stmt, s->v.For.body);
2029 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2030 compiler_use_next_block(c, cleanup);
2031 ADDOP(c, POP_BLOCK);
2032 compiler_pop_fblock(c, LOOP, start);
2033 VISIT_SEQ(c, stmt, s->v.For.orelse);
2034 compiler_use_next_block(c, end);
2035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036}
2037
Yury Selivanov75445082015-05-11 22:57:16 -04002038
2039static int
2040compiler_async_for(struct compiler *c, stmt_ty s)
2041{
2042 static PyObject *stopiter_error = NULL;
2043 basicblock *try, *except, *end, *after_try, *try_cleanup,
2044 *after_loop, *after_loop_else;
2045
2046 if (stopiter_error == NULL) {
2047 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2048 if (stopiter_error == NULL)
2049 return 0;
2050 }
2051
2052 try = compiler_new_block(c);
2053 except = compiler_new_block(c);
2054 end = compiler_new_block(c);
2055 after_try = compiler_new_block(c);
2056 try_cleanup = compiler_new_block(c);
2057 after_loop = compiler_new_block(c);
2058 after_loop_else = compiler_new_block(c);
2059
2060 if (try == NULL || except == NULL || end == NULL
2061 || after_try == NULL || try_cleanup == NULL)
2062 return 0;
2063
2064 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2065 if (!compiler_push_fblock(c, LOOP, try))
2066 return 0;
2067
2068 VISIT(c, expr, s->v.AsyncFor.iter);
2069 ADDOP(c, GET_AITER);
2070 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2071 ADDOP(c, YIELD_FROM);
2072
2073 compiler_use_next_block(c, try);
2074
2075
2076 ADDOP_JREL(c, SETUP_EXCEPT, except);
2077 if (!compiler_push_fblock(c, EXCEPT, try))
2078 return 0;
2079
2080 ADDOP(c, GET_ANEXT);
2081 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2082 ADDOP(c, YIELD_FROM);
2083 VISIT(c, expr, s->v.AsyncFor.target);
2084 ADDOP(c, POP_BLOCK);
2085 compiler_pop_fblock(c, EXCEPT, try);
2086 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2087
2088
2089 compiler_use_next_block(c, except);
2090 ADDOP(c, DUP_TOP);
2091 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2092 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2093 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2094
2095 ADDOP(c, POP_TOP);
2096 ADDOP(c, POP_TOP);
2097 ADDOP(c, POP_TOP);
2098 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2099 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2100 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2101
2102
2103 compiler_use_next_block(c, try_cleanup);
2104 ADDOP(c, END_FINALLY);
2105
2106 compiler_use_next_block(c, after_try);
2107 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2108 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2109
2110 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2111 compiler_pop_fblock(c, LOOP, try);
2112
2113 compiler_use_next_block(c, after_loop);
2114 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2115
2116 compiler_use_next_block(c, after_loop_else);
2117 VISIT_SEQ(c, stmt, s->v.For.orelse);
2118
2119 compiler_use_next_block(c, end);
2120
2121 return 1;
2122}
2123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124static int
2125compiler_while(struct compiler *c, stmt_ty s)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002128 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (constant == 0) {
2131 if (s->v.While.orelse)
2132 VISIT_SEQ(c, stmt, s->v.While.orelse);
2133 return 1;
2134 }
2135 loop = compiler_new_block(c);
2136 end = compiler_new_block(c);
2137 if (constant == -1) {
2138 anchor = compiler_new_block(c);
2139 if (anchor == NULL)
2140 return 0;
2141 }
2142 if (loop == NULL || end == NULL)
2143 return 0;
2144 if (s->v.While.orelse) {
2145 orelse = compiler_new_block(c);
2146 if (orelse == NULL)
2147 return 0;
2148 }
2149 else
2150 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 ADDOP_JREL(c, SETUP_LOOP, end);
2153 compiler_use_next_block(c, loop);
2154 if (!compiler_push_fblock(c, LOOP, loop))
2155 return 0;
2156 if (constant == -1) {
2157 VISIT(c, expr, s->v.While.test);
2158 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2159 }
2160 VISIT_SEQ(c, stmt, s->v.While.body);
2161 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* XXX should the two POP instructions be in a separate block
2164 if there is no else clause ?
2165 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002167 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002169 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 compiler_pop_fblock(c, LOOP, loop);
2171 if (orelse != NULL) /* what if orelse is just pass? */
2172 VISIT_SEQ(c, stmt, s->v.While.orelse);
2173 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176}
2177
2178static int
2179compiler_continue(struct compiler *c)
2180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2182 static const char IN_FINALLY_ERROR_MSG[] =
2183 "'continue' not supported inside 'finally' clause";
2184 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (!c->u->u_nfblocks)
2187 return compiler_error(c, LOOP_ERROR_MSG);
2188 i = c->u->u_nfblocks - 1;
2189 switch (c->u->u_fblock[i].fb_type) {
2190 case LOOP:
2191 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2192 break;
2193 case EXCEPT:
2194 case FINALLY_TRY:
2195 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2196 /* Prevent continue anywhere under a finally
2197 even if hidden in a sub-try or except. */
2198 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2199 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2200 }
2201 if (i == -1)
2202 return compiler_error(c, LOOP_ERROR_MSG);
2203 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2204 break;
2205 case FINALLY_END:
2206 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210}
2211
2212/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213
2214 SETUP_FINALLY L
2215 <code for body>
2216 POP_BLOCK
2217 LOAD_CONST <None>
2218 L: <code for finalbody>
2219 END_FINALLY
2220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 The special instructions use the block stack. Each block
2222 stack entry contains the instruction that created it (here
2223 SETUP_FINALLY), the level of the value stack at the time the
2224 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 Pushes the current value stack level and the label
2228 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 Pops en entry from the block stack, and pops the value
2231 stack until its level is the same as indicated on the
2232 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 Pops a variable number of entries from the *value* stack
2235 and re-raises the exception they specify. The number of
2236 entries popped depends on the (pseudo) exception type.
2237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 The block stack is unwound when an exception is raised:
2239 when a SETUP_FINALLY entry is found, the exception is pushed
2240 onto the value stack (and the exception condition is cleared),
2241 and the interpreter jumps to the label gotten from the block
2242 stack.
2243*/
2244
2245static int
2246compiler_try_finally(struct compiler *c, stmt_ty s)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 basicblock *body, *end;
2249 body = compiler_new_block(c);
2250 end = compiler_new_block(c);
2251 if (body == NULL || end == NULL)
2252 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 ADDOP_JREL(c, SETUP_FINALLY, end);
2255 compiler_use_next_block(c, body);
2256 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2257 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002258 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2259 if (!compiler_try_except(c, s))
2260 return 0;
2261 }
2262 else {
2263 VISIT_SEQ(c, stmt, s->v.Try.body);
2264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 ADDOP(c, POP_BLOCK);
2266 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2269 compiler_use_next_block(c, end);
2270 if (!compiler_push_fblock(c, FINALLY_END, end))
2271 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002272 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 ADDOP(c, END_FINALLY);
2274 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277}
2278
2279/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002280 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 (The contents of the value stack is shown in [], with the top
2282 at the right; 'tb' is trace-back info, 'val' the exception's
2283 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284
2285 Value stack Label Instruction Argument
2286 [] SETUP_EXCEPT L1
2287 [] <code for S>
2288 [] POP_BLOCK
2289 [] JUMP_FORWARD L0
2290
2291 [tb, val, exc] L1: DUP )
2292 [tb, val, exc, exc] <evaluate E1> )
2293 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2294 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2295 [tb, val, exc] POP
2296 [tb, val] <assign to V1> (or POP if no V1)
2297 [tb] POP
2298 [] <code for S1>
2299 JUMP_FORWARD L0
2300
2301 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 .............................etc.......................
2303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2305
2306 [] L0: <next statement>
2307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 Of course, parts are not generated if Vi or Ei is not present.
2309*/
2310static int
2311compiler_try_except(struct compiler *c, stmt_ty s)
2312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002314 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 body = compiler_new_block(c);
2317 except = compiler_new_block(c);
2318 orelse = compiler_new_block(c);
2319 end = compiler_new_block(c);
2320 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2321 return 0;
2322 ADDOP_JREL(c, SETUP_EXCEPT, except);
2323 compiler_use_next_block(c, body);
2324 if (!compiler_push_fblock(c, EXCEPT, body))
2325 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002326 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 ADDOP(c, POP_BLOCK);
2328 compiler_pop_fblock(c, EXCEPT, body);
2329 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002330 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 compiler_use_next_block(c, except);
2332 for (i = 0; i < n; i++) {
2333 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002334 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (!handler->v.ExceptHandler.type && i < n-1)
2336 return compiler_error(c, "default 'except:' must be last");
2337 c->u->u_lineno_set = 0;
2338 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002339 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 except = compiler_new_block(c);
2341 if (except == NULL)
2342 return 0;
2343 if (handler->v.ExceptHandler.type) {
2344 ADDOP(c, DUP_TOP);
2345 VISIT(c, expr, handler->v.ExceptHandler.type);
2346 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2347 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2348 }
2349 ADDOP(c, POP_TOP);
2350 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002351 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002352
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002353 cleanup_end = compiler_new_block(c);
2354 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002355 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002356 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002357
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002358 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2359 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002361 /*
2362 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002363 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002364 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002365 try:
2366 # body
2367 finally:
2368 name = None
2369 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002370 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002372 /* second try: */
2373 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2374 compiler_use_next_block(c, cleanup_body);
2375 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2376 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002378 /* second # body */
2379 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2380 ADDOP(c, POP_BLOCK);
2381 ADDOP(c, POP_EXCEPT);
2382 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002384 /* finally: */
2385 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2386 compiler_use_next_block(c, cleanup_end);
2387 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2388 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002390 /* name = None */
2391 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2392 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002394 /* del name */
2395 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002397 ADDOP(c, END_FINALLY);
2398 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 }
2400 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002401 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002403 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002404 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002405 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406
Guido van Rossumb940e112007-01-10 16:19:56 +00002407 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002408 ADDOP(c, POP_TOP);
2409 compiler_use_next_block(c, cleanup_body);
2410 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2411 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002413 ADDOP(c, POP_EXCEPT);
2414 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 }
2416 ADDOP_JREL(c, JUMP_FORWARD, end);
2417 compiler_use_next_block(c, except);
2418 }
2419 ADDOP(c, END_FINALLY);
2420 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002421 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 compiler_use_next_block(c, end);
2423 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424}
2425
2426static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002427compiler_try(struct compiler *c, stmt_ty s) {
2428 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2429 return compiler_try_finally(c, s);
2430 else
2431 return compiler_try_except(c, s);
2432}
2433
2434
2435static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436compiler_import_as(struct compiler *c, identifier name, identifier asname)
2437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 /* The IMPORT_NAME opcode was already generated. This function
2439 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 If there is a dot in name, we need to split it and emit a
2442 LOAD_ATTR for each name.
2443 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2445 PyUnicode_GET_LENGTH(name), 1);
2446 if (dot == -2)
2447 return -1;
2448 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 Py_ssize_t pos = dot + 1;
2451 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 dot = PyUnicode_FindChar(name, '.', pos,
2454 PyUnicode_GET_LENGTH(name), 1);
2455 if (dot == -2)
2456 return -1;
2457 attr = PyUnicode_Substring(name, pos,
2458 (dot != -1) ? dot :
2459 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (!attr)
2461 return -1;
2462 ADDOP_O(c, LOAD_ATTR, attr, names);
2463 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 }
2466 }
2467 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468}
2469
2470static int
2471compiler_import(struct compiler *c, stmt_ty s)
2472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* The Import node stores a module name like a.b.c as a single
2474 string. This is convenient for all cases except
2475 import a.b.c as d
2476 where we need to parse that string to extract the individual
2477 module names.
2478 XXX Perhaps change the representation to make this case simpler?
2479 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002480 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 for (i = 0; i < n; i++) {
2483 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2484 int r;
2485 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 level = PyLong_FromLong(0);
2488 if (level == NULL)
2489 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 ADDOP_O(c, LOAD_CONST, level, consts);
2492 Py_DECREF(level);
2493 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2494 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (alias->asname) {
2497 r = compiler_import_as(c, alias->name, alias->asname);
2498 if (!r)
2499 return r;
2500 }
2501 else {
2502 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 Py_ssize_t dot = PyUnicode_FindChar(
2504 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002505 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002507 if (tmp == NULL)
2508 return 0;
2509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 Py_DECREF(tmp);
2513 }
2514 if (!r)
2515 return r;
2516 }
2517 }
2518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519}
2520
2521static int
2522compiler_from_import(struct compiler *c, stmt_ty s)
2523{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002524 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 PyObject *names = PyTuple_New(n);
2527 PyObject *level;
2528 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (!empty_string) {
2531 empty_string = PyUnicode_FromString("");
2532 if (!empty_string)
2533 return 0;
2534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (!names)
2537 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 level = PyLong_FromLong(s->v.ImportFrom.level);
2540 if (!level) {
2541 Py_DECREF(names);
2542 return 0;
2543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* build up the names */
2546 for (i = 0; i < n; i++) {
2547 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2548 Py_INCREF(alias->name);
2549 PyTuple_SET_ITEM(names, i, alias->name);
2550 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2553 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2554 Py_DECREF(level);
2555 Py_DECREF(names);
2556 return compiler_error(c, "from __future__ imports must occur "
2557 "at the beginning of the file");
2558 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 ADDOP_O(c, LOAD_CONST, level, consts);
2561 Py_DECREF(level);
2562 ADDOP_O(c, LOAD_CONST, names, consts);
2563 Py_DECREF(names);
2564 if (s->v.ImportFrom.module) {
2565 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2566 }
2567 else {
2568 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2569 }
2570 for (i = 0; i < n; i++) {
2571 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2572 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 assert(n == 1);
2576 ADDOP(c, IMPORT_STAR);
2577 return 1;
2578 }
2579
2580 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2581 store_name = alias->name;
2582 if (alias->asname)
2583 store_name = alias->asname;
2584
2585 if (!compiler_nameop(c, store_name, Store)) {
2586 Py_DECREF(names);
2587 return 0;
2588 }
2589 }
2590 /* remove imported module */
2591 ADDOP(c, POP_TOP);
2592 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593}
2594
2595static int
2596compiler_assert(struct compiler *c, stmt_ty s)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 static PyObject *assertion_error = NULL;
2599 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002600 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
Georg Brandl8334fd92010-12-04 10:26:46 +00002602 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 return 1;
2604 if (assertion_error == NULL) {
2605 assertion_error = PyUnicode_InternFromString("AssertionError");
2606 if (assertion_error == NULL)
2607 return 0;
2608 }
2609 if (s->v.Assert.test->kind == Tuple_kind &&
2610 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002611 msg = PyUnicode_FromString("assertion is always true, "
2612 "perhaps remove parentheses?");
2613 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002615 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2616 c->c_filename, c->u->u_lineno,
2617 NULL, NULL) == -1) {
2618 Py_DECREF(msg);
2619 return 0;
2620 }
2621 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 }
2623 VISIT(c, expr, s->v.Assert.test);
2624 end = compiler_new_block(c);
2625 if (end == NULL)
2626 return 0;
2627 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2628 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2629 if (s->v.Assert.msg) {
2630 VISIT(c, expr, s->v.Assert.msg);
2631 ADDOP_I(c, CALL_FUNCTION, 1);
2632 }
2633 ADDOP_I(c, RAISE_VARARGS, 1);
2634 compiler_use_next_block(c, end);
2635 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636}
2637
2638static int
2639compiler_visit_stmt(struct compiler *c, stmt_ty s)
2640{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002641 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 /* Always assign a lineno to the next instruction for a stmt. */
2644 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002645 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 switch (s->kind) {
2649 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002650 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 case ClassDef_kind:
2652 return compiler_class(c, s);
2653 case Return_kind:
2654 if (c->u->u_ste->ste_type != FunctionBlock)
2655 return compiler_error(c, "'return' outside function");
2656 if (s->v.Return.value) {
2657 VISIT(c, expr, s->v.Return.value);
2658 }
2659 else
2660 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2661 ADDOP(c, RETURN_VALUE);
2662 break;
2663 case Delete_kind:
2664 VISIT_SEQ(c, expr, s->v.Delete.targets)
2665 break;
2666 case Assign_kind:
2667 n = asdl_seq_LEN(s->v.Assign.targets);
2668 VISIT(c, expr, s->v.Assign.value);
2669 for (i = 0; i < n; i++) {
2670 if (i < n - 1)
2671 ADDOP(c, DUP_TOP);
2672 VISIT(c, expr,
2673 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2674 }
2675 break;
2676 case AugAssign_kind:
2677 return compiler_augassign(c, s);
2678 case For_kind:
2679 return compiler_for(c, s);
2680 case While_kind:
2681 return compiler_while(c, s);
2682 case If_kind:
2683 return compiler_if(c, s);
2684 case Raise_kind:
2685 n = 0;
2686 if (s->v.Raise.exc) {
2687 VISIT(c, expr, s->v.Raise.exc);
2688 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002689 if (s->v.Raise.cause) {
2690 VISIT(c, expr, s->v.Raise.cause);
2691 n++;
2692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002694 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002696 case Try_kind:
2697 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 case Assert_kind:
2699 return compiler_assert(c, s);
2700 case Import_kind:
2701 return compiler_import(c, s);
2702 case ImportFrom_kind:
2703 return compiler_from_import(c, s);
2704 case Global_kind:
2705 case Nonlocal_kind:
2706 break;
2707 case Expr_kind:
2708 if (c->c_interactive && c->c_nestlevel <= 1) {
2709 VISIT(c, expr, s->v.Expr.value);
2710 ADDOP(c, PRINT_EXPR);
2711 }
2712 else if (s->v.Expr.value->kind != Str_kind &&
2713 s->v.Expr.value->kind != Num_kind) {
2714 VISIT(c, expr, s->v.Expr.value);
2715 ADDOP(c, POP_TOP);
2716 }
2717 break;
2718 case Pass_kind:
2719 break;
2720 case Break_kind:
2721 if (!compiler_in_loop(c))
2722 return compiler_error(c, "'break' outside loop");
2723 ADDOP(c, BREAK_LOOP);
2724 break;
2725 case Continue_kind:
2726 return compiler_continue(c);
2727 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002728 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002729 case AsyncFunctionDef_kind:
2730 return compiler_function(c, s, 1);
2731 case AsyncWith_kind:
2732 return compiler_async_with(c, s, 0);
2733 case AsyncFor_kind:
2734 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 }
Yury Selivanov75445082015-05-11 22:57:16 -04002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738}
2739
2740static int
2741unaryop(unaryop_ty op)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 switch (op) {
2744 case Invert:
2745 return UNARY_INVERT;
2746 case Not:
2747 return UNARY_NOT;
2748 case UAdd:
2749 return UNARY_POSITIVE;
2750 case USub:
2751 return UNARY_NEGATIVE;
2752 default:
2753 PyErr_Format(PyExc_SystemError,
2754 "unary op %d should not be possible", op);
2755 return 0;
2756 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757}
2758
2759static int
2760binop(struct compiler *c, operator_ty op)
2761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 switch (op) {
2763 case Add:
2764 return BINARY_ADD;
2765 case Sub:
2766 return BINARY_SUBTRACT;
2767 case Mult:
2768 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002769 case MatMult:
2770 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 case Div:
2772 return BINARY_TRUE_DIVIDE;
2773 case Mod:
2774 return BINARY_MODULO;
2775 case Pow:
2776 return BINARY_POWER;
2777 case LShift:
2778 return BINARY_LSHIFT;
2779 case RShift:
2780 return BINARY_RSHIFT;
2781 case BitOr:
2782 return BINARY_OR;
2783 case BitXor:
2784 return BINARY_XOR;
2785 case BitAnd:
2786 return BINARY_AND;
2787 case FloorDiv:
2788 return BINARY_FLOOR_DIVIDE;
2789 default:
2790 PyErr_Format(PyExc_SystemError,
2791 "binary op %d should not be possible", op);
2792 return 0;
2793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794}
2795
2796static int
2797cmpop(cmpop_ty op)
2798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 switch (op) {
2800 case Eq:
2801 return PyCmp_EQ;
2802 case NotEq:
2803 return PyCmp_NE;
2804 case Lt:
2805 return PyCmp_LT;
2806 case LtE:
2807 return PyCmp_LE;
2808 case Gt:
2809 return PyCmp_GT;
2810 case GtE:
2811 return PyCmp_GE;
2812 case Is:
2813 return PyCmp_IS;
2814 case IsNot:
2815 return PyCmp_IS_NOT;
2816 case In:
2817 return PyCmp_IN;
2818 case NotIn:
2819 return PyCmp_NOT_IN;
2820 default:
2821 return PyCmp_BAD;
2822 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002823}
2824
2825static int
2826inplace_binop(struct compiler *c, operator_ty op)
2827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 switch (op) {
2829 case Add:
2830 return INPLACE_ADD;
2831 case Sub:
2832 return INPLACE_SUBTRACT;
2833 case Mult:
2834 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002835 case MatMult:
2836 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 case Div:
2838 return INPLACE_TRUE_DIVIDE;
2839 case Mod:
2840 return INPLACE_MODULO;
2841 case Pow:
2842 return INPLACE_POWER;
2843 case LShift:
2844 return INPLACE_LSHIFT;
2845 case RShift:
2846 return INPLACE_RSHIFT;
2847 case BitOr:
2848 return INPLACE_OR;
2849 case BitXor:
2850 return INPLACE_XOR;
2851 case BitAnd:
2852 return INPLACE_AND;
2853 case FloorDiv:
2854 return INPLACE_FLOOR_DIVIDE;
2855 default:
2856 PyErr_Format(PyExc_SystemError,
2857 "inplace binary op %d should not be possible", op);
2858 return 0;
2859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860}
2861
2862static int
2863compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2864{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002865 int op, scope;
2866 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 PyObject *dict = c->u->u_names;
2870 PyObject *mangled;
2871 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 mangled = _Py_Mangle(c->u->u_private, name);
2874 if (!mangled)
2875 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002876
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002877 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2878 PyUnicode_CompareWithASCIIString(name, "True") &&
2879 PyUnicode_CompareWithASCIIString(name, "False"));
2880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 op = 0;
2882 optype = OP_NAME;
2883 scope = PyST_GetScope(c->u->u_ste, mangled);
2884 switch (scope) {
2885 case FREE:
2886 dict = c->u->u_freevars;
2887 optype = OP_DEREF;
2888 break;
2889 case CELL:
2890 dict = c->u->u_cellvars;
2891 optype = OP_DEREF;
2892 break;
2893 case LOCAL:
2894 if (c->u->u_ste->ste_type == FunctionBlock)
2895 optype = OP_FAST;
2896 break;
2897 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002898 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 optype = OP_GLOBAL;
2900 break;
2901 case GLOBAL_EXPLICIT:
2902 optype = OP_GLOBAL;
2903 break;
2904 default:
2905 /* scope can be 0 */
2906 break;
2907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002910 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 switch (optype) {
2913 case OP_DEREF:
2914 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002915 case Load:
2916 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2917 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 case Store: op = STORE_DEREF; break;
2919 case AugLoad:
2920 case AugStore:
2921 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002922 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 case Param:
2924 default:
2925 PyErr_SetString(PyExc_SystemError,
2926 "param invalid for deref variable");
2927 return 0;
2928 }
2929 break;
2930 case OP_FAST:
2931 switch (ctx) {
2932 case Load: op = LOAD_FAST; break;
2933 case Store: op = STORE_FAST; break;
2934 case Del: op = DELETE_FAST; break;
2935 case AugLoad:
2936 case AugStore:
2937 break;
2938 case Param:
2939 default:
2940 PyErr_SetString(PyExc_SystemError,
2941 "param invalid for local variable");
2942 return 0;
2943 }
2944 ADDOP_O(c, op, mangled, varnames);
2945 Py_DECREF(mangled);
2946 return 1;
2947 case OP_GLOBAL:
2948 switch (ctx) {
2949 case Load: op = LOAD_GLOBAL; break;
2950 case Store: op = STORE_GLOBAL; break;
2951 case Del: op = DELETE_GLOBAL; break;
2952 case AugLoad:
2953 case AugStore:
2954 break;
2955 case Param:
2956 default:
2957 PyErr_SetString(PyExc_SystemError,
2958 "param invalid for global variable");
2959 return 0;
2960 }
2961 break;
2962 case OP_NAME:
2963 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002964 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 case Store: op = STORE_NAME; break;
2966 case Del: op = DELETE_NAME; break;
2967 case AugLoad:
2968 case AugStore:
2969 break;
2970 case Param:
2971 default:
2972 PyErr_SetString(PyExc_SystemError,
2973 "param invalid for name variable");
2974 return 0;
2975 }
2976 break;
2977 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 assert(op);
2980 arg = compiler_add_o(c, dict, mangled);
2981 Py_DECREF(mangled);
2982 if (arg < 0)
2983 return 0;
2984 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985}
2986
2987static int
2988compiler_boolop(struct compiler *c, expr_ty e)
2989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002991 int jumpi;
2992 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 assert(e->kind == BoolOp_kind);
2996 if (e->v.BoolOp.op == And)
2997 jumpi = JUMP_IF_FALSE_OR_POP;
2998 else
2999 jumpi = JUMP_IF_TRUE_OR_POP;
3000 end = compiler_new_block(c);
3001 if (end == NULL)
3002 return 0;
3003 s = e->v.BoolOp.values;
3004 n = asdl_seq_LEN(s) - 1;
3005 assert(n >= 0);
3006 for (i = 0; i < n; ++i) {
3007 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3008 ADDOP_JABS(c, jumpi, end);
3009 }
3010 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3011 compiler_use_next_block(c, end);
3012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013}
3014
3015static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003016starunpack_helper(struct compiler *c, asdl_seq *elts,
3017 int single_op, int inner_op, int outer_op)
3018{
3019 Py_ssize_t n = asdl_seq_LEN(elts);
3020 Py_ssize_t i, nsubitems = 0, nseen = 0;
3021 for (i = 0; i < n; i++) {
3022 expr_ty elt = asdl_seq_GET(elts, i);
3023 if (elt->kind == Starred_kind) {
3024 if (nseen) {
3025 ADDOP_I(c, inner_op, nseen);
3026 nseen = 0;
3027 nsubitems++;
3028 }
3029 VISIT(c, expr, elt->v.Starred.value);
3030 nsubitems++;
3031 }
3032 else {
3033 VISIT(c, expr, elt);
3034 nseen++;
3035 }
3036 }
3037 if (nsubitems) {
3038 if (nseen) {
3039 ADDOP_I(c, inner_op, nseen);
3040 nsubitems++;
3041 }
3042 ADDOP_I(c, outer_op, nsubitems);
3043 }
3044 else
3045 ADDOP_I(c, single_op, nseen);
3046 return 1;
3047}
3048
3049static int
3050assignment_helper(struct compiler *c, asdl_seq *elts)
3051{
3052 Py_ssize_t n = asdl_seq_LEN(elts);
3053 Py_ssize_t i;
3054 int seen_star = 0;
3055 for (i = 0; i < n; i++) {
3056 expr_ty elt = asdl_seq_GET(elts, i);
3057 if (elt->kind == Starred_kind && !seen_star) {
3058 if ((i >= (1 << 8)) ||
3059 (n-i-1 >= (INT_MAX >> 8)))
3060 return compiler_error(c,
3061 "too many expressions in "
3062 "star-unpacking assignment");
3063 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3064 seen_star = 1;
3065 asdl_seq_SET(elts, i, elt->v.Starred.value);
3066 }
3067 else if (elt->kind == Starred_kind) {
3068 return compiler_error(c,
3069 "two starred expressions in assignment");
3070 }
3071 }
3072 if (!seen_star) {
3073 ADDOP_I(c, UNPACK_SEQUENCE, n);
3074 }
3075 VISIT_SEQ(c, expr, elts);
3076 return 1;
3077}
3078
3079static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080compiler_list(struct compiler *c, expr_ty e)
3081{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003082 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003084 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003086 else if (e->v.List.ctx == Load) {
3087 return starunpack_helper(c, elts,
3088 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003090 else
3091 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093}
3094
3095static int
3096compiler_tuple(struct compiler *c, expr_ty e)
3097{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003098 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003100 return assignment_helper(c, elts);
3101 }
3102 else if (e->v.Tuple.ctx == Load) {
3103 return starunpack_helper(c, elts,
3104 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3105 }
3106 else
3107 VISIT_SEQ(c, expr, elts);
3108 return 1;
3109}
3110
3111static int
3112compiler_set(struct compiler *c, expr_ty e)
3113{
3114 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3115 BUILD_SET, BUILD_SET_UNPACK);
3116}
3117
3118static int
3119compiler_dict(struct compiler *c, expr_ty e)
3120{
3121 Py_ssize_t i, n, containers, elements;
3122 int is_unpacking = 0;
3123 n = asdl_seq_LEN(e->v.Dict.values);
3124 containers = 0;
3125 elements = 0;
3126 for (i = 0; i < n; i++) {
3127 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3128 if (elements == 0xFFFF || (elements && is_unpacking)) {
3129 ADDOP_I(c, BUILD_MAP, elements);
3130 containers++;
3131 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003133 if (is_unpacking) {
3134 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3135 containers++;
3136 }
3137 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003138 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003139 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003140 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 }
3142 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003143 if (elements || containers == 0) {
3144 ADDOP_I(c, BUILD_MAP, elements);
3145 containers++;
3146 }
3147 /* If there is more than one dict, they need to be merged into a new
3148 * dict. If there is one dict and it's an unpacking, then it needs
3149 * to be copied into a new dict." */
3150 while (containers > 1 || is_unpacking) {
3151 int oparg = containers < 255 ? containers : 255;
3152 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3153 containers -= (oparg - 1);
3154 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 }
3156 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157}
3158
3159static int
3160compiler_compare(struct compiler *c, expr_ty e)
3161{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003162 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3166 VISIT(c, expr, e->v.Compare.left);
3167 n = asdl_seq_LEN(e->v.Compare.ops);
3168 assert(n > 0);
3169 if (n > 1) {
3170 cleanup = compiler_new_block(c);
3171 if (cleanup == NULL)
3172 return 0;
3173 VISIT(c, expr,
3174 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3175 }
3176 for (i = 1; i < n; i++) {
3177 ADDOP(c, DUP_TOP);
3178 ADDOP(c, ROT_THREE);
3179 ADDOP_I(c, COMPARE_OP,
3180 cmpop((cmpop_ty)(asdl_seq_GET(
3181 e->v.Compare.ops, i - 1))));
3182 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3183 NEXT_BLOCK(c);
3184 if (i < (n - 1))
3185 VISIT(c, expr,
3186 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3187 }
3188 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3189 ADDOP_I(c, COMPARE_OP,
3190 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3191 if (n > 1) {
3192 basicblock *end = compiler_new_block(c);
3193 if (end == NULL)
3194 return 0;
3195 ADDOP_JREL(c, JUMP_FORWARD, end);
3196 compiler_use_next_block(c, cleanup);
3197 ADDOP(c, ROT_TWO);
3198 ADDOP(c, POP_TOP);
3199 compiler_use_next_block(c, end);
3200 }
3201 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202}
3203
3204static int
3205compiler_call(struct compiler *c, expr_ty e)
3206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 VISIT(c, expr, e->v.Call.func);
3208 return compiler_call_helper(c, 0,
3209 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003210 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003211}
3212
Eric V. Smith235a6f02015-09-19 14:51:32 -04003213static int
3214compiler_joined_str(struct compiler *c, expr_ty e)
3215{
3216 /* Concatenate parts of a string using ''.join(parts). There are
3217 probably better ways of doing this.
3218
3219 This is used for constructs like "'x=' f'{42}'", which have to
3220 be evaluated at compile time. */
3221
3222 static PyObject *empty_string;
3223 static PyObject *join_string;
3224
3225 if (!empty_string) {
3226 empty_string = PyUnicode_FromString("");
3227 if (!empty_string)
3228 return 0;
3229 }
3230 if (!join_string) {
3231 join_string = PyUnicode_FromString("join");
3232 if (!join_string)
3233 return 0;
3234 }
3235
3236 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3237 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3238 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3239 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3240 ADDOP_I(c, CALL_FUNCTION, 1);
3241 return 1;
3242}
3243
3244/* Note that this code uses the builtin functions format(), str(),
3245 repr(), and ascii(). You can break this code, or make it do odd
3246 things, by redefining those functions. */
3247static int
3248compiler_formatted_value(struct compiler *c, expr_ty e)
3249{
3250 PyObject *conversion_name = NULL;
3251
3252 static PyObject *format_string;
3253 static PyObject *str_string;
3254 static PyObject *repr_string;
3255 static PyObject *ascii_string;
3256
3257 if (!format_string) {
3258 format_string = PyUnicode_InternFromString("format");
3259 if (!format_string)
3260 return 0;
3261 }
3262
3263 if (!str_string) {
3264 str_string = PyUnicode_InternFromString("str");
3265 if (!str_string)
3266 return 0;
3267 }
3268
3269 if (!repr_string) {
3270 repr_string = PyUnicode_InternFromString("repr");
3271 if (!repr_string)
3272 return 0;
3273 }
3274 if (!ascii_string) {
3275 ascii_string = PyUnicode_InternFromString("ascii");
3276 if (!ascii_string)
3277 return 0;
3278 }
3279
3280 ADDOP_NAME(c, LOAD_GLOBAL, format_string, names);
3281
3282 /* If needed, convert via str, repr, or ascii. */
3283 if (e->v.FormattedValue.conversion != -1) {
3284 switch (e->v.FormattedValue.conversion) {
3285 case 's':
3286 conversion_name = str_string;
3287 break;
3288 case 'r':
3289 conversion_name = repr_string;
3290 break;
3291 case 'a':
3292 conversion_name = ascii_string;
3293 break;
3294 default:
3295 PyErr_SetString(PyExc_SystemError,
3296 "Unrecognized conversion character");
3297 return 0;
3298 }
3299 ADDOP_NAME(c, LOAD_GLOBAL, conversion_name, names);
3300 }
3301
3302 /* Evaluate the value. */
3303 VISIT(c, expr, e->v.FormattedValue.value);
3304
3305 /* If needed, convert via str, repr, or ascii. */
3306 if (conversion_name) {
3307 /* Call the function we previously pushed. */
3308 ADDOP_I(c, CALL_FUNCTION, 1);
3309 }
3310
3311 /* If we have a format spec, use format(value, format_spec). Otherwise,
3312 use the single argument form. */
3313 if (e->v.FormattedValue.format_spec) {
3314 VISIT(c, expr, e->v.FormattedValue.format_spec);
3315 ADDOP_I(c, CALL_FUNCTION, 2);
3316 } else {
3317 /* No format spec specified, call format(value). */
3318 ADDOP_I(c, CALL_FUNCTION, 1);
3319 }
3320
3321 return 1;
3322}
3323
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003324/* shared code between compiler_call and compiler_class */
3325static int
3326compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003327 Py_ssize_t n, /* Args already pushed */
3328 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003329 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003332 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003333
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003334 /* the number of tuples and dictionaries on the stack */
3335 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3336
3337 nkw = 0;
3338 nseen = 0; /* the number of positional arguments on the stack */
3339 nelts = asdl_seq_LEN(args);
3340 for (i = 0; i < nelts; i++) {
3341 expr_ty elt = asdl_seq_GET(args, i);
3342 if (elt->kind == Starred_kind) {
3343 /* A star-arg. If we've seen positional arguments,
3344 pack the positional arguments into a
3345 tuple. */
3346 if (nseen) {
3347 ADDOP_I(c, BUILD_TUPLE, nseen);
3348 nseen = 0;
3349 nsubargs++;
3350 }
3351 VISIT(c, expr, elt->v.Starred.value);
3352 nsubargs++;
3353 }
3354 else if (nsubargs) {
3355 /* We've seen star-args already, so we
3356 count towards items-to-pack-into-tuple. */
3357 VISIT(c, expr, elt);
3358 nseen++;
3359 }
3360 else {
3361 /* Positional arguments before star-arguments
3362 are left on the stack. */
3363 VISIT(c, expr, elt);
3364 n++;
3365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003367 if (nseen) {
3368 /* Pack up any trailing positional arguments. */
3369 ADDOP_I(c, BUILD_TUPLE, nseen);
3370 nsubargs++;
3371 }
3372 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003374 if (nsubargs > 1) {
3375 /* If we ended up with more than one stararg, we need
3376 to concatenate them into a single sequence. */
3377 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3378 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003380
3381 /* Same dance again for keyword arguments */
3382 nseen = 0; /* the number of keyword arguments on the stack following */
3383 nelts = asdl_seq_LEN(keywords);
3384 for (i = 0; i < nelts; i++) {
3385 keyword_ty kw = asdl_seq_GET(keywords, i);
3386 if (kw->arg == NULL) {
3387 /* A keyword argument unpacking. */
3388 if (nseen) {
3389 ADDOP_I(c, BUILD_MAP, nseen);
3390 nseen = 0;
3391 nsubkwargs++;
3392 }
3393 VISIT(c, expr, kw->value);
3394 nsubkwargs++;
3395 }
3396 else if (nsubkwargs) {
3397 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003398 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003399 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003400 nseen++;
3401 }
3402 else {
3403 /* keyword argument */
3404 VISIT(c, keyword, kw)
3405 nkw++;
3406 }
3407 }
3408 if (nseen) {
3409 /* Pack up any trailing keyword arguments. */
3410 ADDOP_I(c, BUILD_MAP, nseen);
3411 nsubkwargs++;
3412 }
3413 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003415 if (nsubkwargs > 1) {
3416 /* Pack it all up */
3417 int function_pos = n + (code & 1) + nkw + 1;
3418 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003421 assert(n < 1<<8);
3422 assert(nkw < 1<<24);
3423 n |= nkw << 8;
3424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 switch (code) {
3426 case 0:
3427 ADDOP_I(c, CALL_FUNCTION, n);
3428 break;
3429 case 1:
3430 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3431 break;
3432 case 2:
3433 ADDOP_I(c, CALL_FUNCTION_KW, n);
3434 break;
3435 case 3:
3436 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3437 break;
3438 }
3439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440}
3441
Nick Coghlan650f0d02007-04-15 12:05:43 +00003442
3443/* List and set comprehensions and generator expressions work by creating a
3444 nested function to perform the actual iteration. This means that the
3445 iteration variables don't leak into the current scope.
3446 The defined function is called immediately following its definition, with the
3447 result of that call being the result of the expression.
3448 The LC/SC version returns the populated container, while the GE version is
3449 flagged in symtable.c as a generator, so it returns the generator object
3450 when the function is called.
3451 This code *knows* that the loop cannot contain break, continue, or return,
3452 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3453
3454 Possible cleanups:
3455 - iterate over the generator sequence instead of using recursion
3456*/
3457
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459compiler_comprehension_generator(struct compiler *c,
3460 asdl_seq *generators, int gen_index,
3461 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 /* generate code for the iterator, then each of the ifs,
3464 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 comprehension_ty gen;
3467 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003468 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 start = compiler_new_block(c);
3471 skip = compiler_new_block(c);
3472 if_cleanup = compiler_new_block(c);
3473 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3476 anchor == NULL)
3477 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 if (gen_index == 0) {
3482 /* Receive outermost iter as an implicit argument */
3483 c->u->u_argcount = 1;
3484 ADDOP_I(c, LOAD_FAST, 0);
3485 }
3486 else {
3487 /* Sub-iter - calculate on the fly */
3488 VISIT(c, expr, gen->iter);
3489 ADDOP(c, GET_ITER);
3490 }
3491 compiler_use_next_block(c, start);
3492 ADDOP_JREL(c, FOR_ITER, anchor);
3493 NEXT_BLOCK(c);
3494 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* XXX this needs to be cleaned up...a lot! */
3497 n = asdl_seq_LEN(gen->ifs);
3498 for (i = 0; i < n; i++) {
3499 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3500 VISIT(c, expr, e);
3501 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3502 NEXT_BLOCK(c);
3503 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 if (++gen_index < asdl_seq_LEN(generators))
3506 if (!compiler_comprehension_generator(c,
3507 generators, gen_index,
3508 elt, val, type))
3509 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 /* only append after the last for generator */
3512 if (gen_index >= asdl_seq_LEN(generators)) {
3513 /* comprehension specific code */
3514 switch (type) {
3515 case COMP_GENEXP:
3516 VISIT(c, expr, elt);
3517 ADDOP(c, YIELD_VALUE);
3518 ADDOP(c, POP_TOP);
3519 break;
3520 case COMP_LISTCOMP:
3521 VISIT(c, expr, elt);
3522 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3523 break;
3524 case COMP_SETCOMP:
3525 VISIT(c, expr, elt);
3526 ADDOP_I(c, SET_ADD, gen_index + 1);
3527 break;
3528 case COMP_DICTCOMP:
3529 /* With 'd[k] = v', v is evaluated before k, so we do
3530 the same. */
3531 VISIT(c, expr, val);
3532 VISIT(c, expr, elt);
3533 ADDOP_I(c, MAP_ADD, gen_index + 1);
3534 break;
3535 default:
3536 return 0;
3537 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 compiler_use_next_block(c, skip);
3540 }
3541 compiler_use_next_block(c, if_cleanup);
3542 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3543 compiler_use_next_block(c, anchor);
3544
3545 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546}
3547
3548static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003549compiler_comprehension(struct compiler *c, expr_ty e, int type,
3550 identifier name, asdl_seq *generators, expr_ty elt,
3551 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 PyCodeObject *co = NULL;
3554 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003555 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 outermost_iter = ((comprehension_ty)
3558 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003559
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003560 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3561 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 if (type != COMP_GENEXP) {
3565 int op;
3566 switch (type) {
3567 case COMP_LISTCOMP:
3568 op = BUILD_LIST;
3569 break;
3570 case COMP_SETCOMP:
3571 op = BUILD_SET;
3572 break;
3573 case COMP_DICTCOMP:
3574 op = BUILD_MAP;
3575 break;
3576 default:
3577 PyErr_Format(PyExc_SystemError,
3578 "unknown comprehension type %d", type);
3579 goto error_in_scope;
3580 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 ADDOP_I(c, op, 0);
3583 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 if (!compiler_comprehension_generator(c, generators, 0, elt,
3586 val, type))
3587 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 if (type != COMP_GENEXP) {
3590 ADDOP(c, RETURN_VALUE);
3591 }
3592
3593 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003594 qualname = c->u->u_qualname;
3595 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003597 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 goto error;
3599
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003600 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003602 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 Py_DECREF(co);
3604
3605 VISIT(c, expr, outermost_iter);
3606 ADDOP(c, GET_ITER);
3607 ADDOP_I(c, CALL_FUNCTION, 1);
3608 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003609error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003611error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003612 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 Py_XDECREF(co);
3614 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003615}
3616
3617static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618compiler_genexp(struct compiler *c, expr_ty e)
3619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 static identifier name;
3621 if (!name) {
3622 name = PyUnicode_FromString("<genexpr>");
3623 if (!name)
3624 return 0;
3625 }
3626 assert(e->kind == GeneratorExp_kind);
3627 return compiler_comprehension(c, e, COMP_GENEXP, name,
3628 e->v.GeneratorExp.generators,
3629 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003633compiler_listcomp(struct compiler *c, expr_ty e)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 static identifier name;
3636 if (!name) {
3637 name = PyUnicode_FromString("<listcomp>");
3638 if (!name)
3639 return 0;
3640 }
3641 assert(e->kind == ListComp_kind);
3642 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3643 e->v.ListComp.generators,
3644 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003645}
3646
3647static int
3648compiler_setcomp(struct compiler *c, expr_ty e)
3649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 static identifier name;
3651 if (!name) {
3652 name = PyUnicode_FromString("<setcomp>");
3653 if (!name)
3654 return 0;
3655 }
3656 assert(e->kind == SetComp_kind);
3657 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3658 e->v.SetComp.generators,
3659 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003660}
3661
3662
3663static int
3664compiler_dictcomp(struct compiler *c, expr_ty e)
3665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 static identifier name;
3667 if (!name) {
3668 name = PyUnicode_FromString("<dictcomp>");
3669 if (!name)
3670 return 0;
3671 }
3672 assert(e->kind == DictComp_kind);
3673 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3674 e->v.DictComp.generators,
3675 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003676}
3677
3678
3679static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680compiler_visit_keyword(struct compiler *c, keyword_ty k)
3681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3683 VISIT(c, expr, k->value);
3684 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685}
3686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688 whether they are true or false.
3689
3690 Return values: 1 for true, 0 for false, -1 for non-constant.
3691 */
3692
3693static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003694expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 char *id;
3697 switch (e->kind) {
3698 case Ellipsis_kind:
3699 return 1;
3700 case Num_kind:
3701 return PyObject_IsTrue(e->v.Num.n);
3702 case Str_kind:
3703 return PyObject_IsTrue(e->v.Str.s);
3704 case Name_kind:
3705 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003706 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003707 if (id && strcmp(id, "__debug__") == 0)
3708 return !c->c_optimize;
3709 return -1;
3710 case NameConstant_kind: {
3711 PyObject *o = e->v.NameConstant.value;
3712 if (o == Py_None)
3713 return 0;
3714 else if (o == Py_True)
3715 return 1;
3716 else if (o == Py_False)
3717 return 0;
3718 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 default:
3720 return -1;
3721 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722}
3723
Yury Selivanov75445082015-05-11 22:57:16 -04003724
3725/*
3726 Implements the async with statement.
3727
3728 The semantics outlined in that PEP are as follows:
3729
3730 async with EXPR as VAR:
3731 BLOCK
3732
3733 It is implemented roughly as:
3734
3735 context = EXPR
3736 exit = context.__aexit__ # not calling it
3737 value = await context.__aenter__()
3738 try:
3739 VAR = value # if VAR present in the syntax
3740 BLOCK
3741 finally:
3742 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003743 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003744 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003745 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003746 if not (await exit(*exc)):
3747 raise
3748 */
3749static int
3750compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3751{
3752 basicblock *block, *finally;
3753 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3754
3755 assert(s->kind == AsyncWith_kind);
3756
3757 block = compiler_new_block(c);
3758 finally = compiler_new_block(c);
3759 if (!block || !finally)
3760 return 0;
3761
3762 /* Evaluate EXPR */
3763 VISIT(c, expr, item->context_expr);
3764
3765 ADDOP(c, BEFORE_ASYNC_WITH);
3766 ADDOP(c, GET_AWAITABLE);
3767 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3768 ADDOP(c, YIELD_FROM);
3769
3770 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3771
3772 /* SETUP_ASYNC_WITH pushes a finally block. */
3773 compiler_use_next_block(c, block);
3774 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3775 return 0;
3776 }
3777
3778 if (item->optional_vars) {
3779 VISIT(c, expr, item->optional_vars);
3780 }
3781 else {
3782 /* Discard result from context.__aenter__() */
3783 ADDOP(c, POP_TOP);
3784 }
3785
3786 pos++;
3787 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3788 /* BLOCK code */
3789 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3790 else if (!compiler_async_with(c, s, pos))
3791 return 0;
3792
3793 /* End of try block; start the finally block */
3794 ADDOP(c, POP_BLOCK);
3795 compiler_pop_fblock(c, FINALLY_TRY, block);
3796
3797 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3798 compiler_use_next_block(c, finally);
3799 if (!compiler_push_fblock(c, FINALLY_END, finally))
3800 return 0;
3801
3802 /* Finally block starts; context.__exit__ is on the stack under
3803 the exception or return information. Just issue our magic
3804 opcode. */
3805 ADDOP(c, WITH_CLEANUP_START);
3806
3807 ADDOP(c, GET_AWAITABLE);
3808 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3809 ADDOP(c, YIELD_FROM);
3810
3811 ADDOP(c, WITH_CLEANUP_FINISH);
3812
3813 /* Finally block ends. */
3814 ADDOP(c, END_FINALLY);
3815 compiler_pop_fblock(c, FINALLY_END, finally);
3816 return 1;
3817}
3818
3819
Guido van Rossumc2e20742006-02-27 22:32:47 +00003820/*
3821 Implements the with statement from PEP 343.
3822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003824
3825 with EXPR as VAR:
3826 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827
Guido van Rossumc2e20742006-02-27 22:32:47 +00003828 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829
Thomas Wouters477c8d52006-05-27 19:21:47 +00003830 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003831 exit = context.__exit__ # not calling it
3832 value = context.__enter__()
3833 try:
3834 VAR = value # if VAR present in the syntax
3835 BLOCK
3836 finally:
3837 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003838 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003839 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003840 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003841 exit(*exc)
3842 */
3843static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003844compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003845{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003846 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003847 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003848
3849 assert(s->kind == With_kind);
3850
Guido van Rossumc2e20742006-02-27 22:32:47 +00003851 block = compiler_new_block(c);
3852 finally = compiler_new_block(c);
3853 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003854 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003855
Thomas Wouters477c8d52006-05-27 19:21:47 +00003856 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003857 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003858 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003859
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003860 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003861 compiler_use_next_block(c, block);
3862 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003863 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003864 }
3865
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003866 if (item->optional_vars) {
3867 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003868 }
3869 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003871 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003872 }
3873
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003874 pos++;
3875 if (pos == asdl_seq_LEN(s->v.With.items))
3876 /* BLOCK code */
3877 VISIT_SEQ(c, stmt, s->v.With.body)
3878 else if (!compiler_with(c, s, pos))
3879 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003880
3881 /* End of try block; start the finally block */
3882 ADDOP(c, POP_BLOCK);
3883 compiler_pop_fblock(c, FINALLY_TRY, block);
3884
3885 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3886 compiler_use_next_block(c, finally);
3887 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003888 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003889
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003890 /* Finally block starts; context.__exit__ is on the stack under
3891 the exception or return information. Just issue our magic
3892 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003893 ADDOP(c, WITH_CLEANUP_START);
3894 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003895
3896 /* Finally block ends. */
3897 ADDOP(c, END_FINALLY);
3898 compiler_pop_fblock(c, FINALLY_END, finally);
3899 return 1;
3900}
3901
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902static int
3903compiler_visit_expr(struct compiler *c, expr_ty e)
3904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 /* If expr e has a different line number than the last expr/stmt,
3906 set a new line number for the next instruction.
3907 */
3908 if (e->lineno > c->u->u_lineno) {
3909 c->u->u_lineno = e->lineno;
3910 c->u->u_lineno_set = 0;
3911 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003912 /* Updating the column offset is always harmless. */
3913 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 switch (e->kind) {
3915 case BoolOp_kind:
3916 return compiler_boolop(c, e);
3917 case BinOp_kind:
3918 VISIT(c, expr, e->v.BinOp.left);
3919 VISIT(c, expr, e->v.BinOp.right);
3920 ADDOP(c, binop(c, e->v.BinOp.op));
3921 break;
3922 case UnaryOp_kind:
3923 VISIT(c, expr, e->v.UnaryOp.operand);
3924 ADDOP(c, unaryop(e->v.UnaryOp.op));
3925 break;
3926 case Lambda_kind:
3927 return compiler_lambda(c, e);
3928 case IfExp_kind:
3929 return compiler_ifexp(c, e);
3930 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003931 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003933 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 case GeneratorExp_kind:
3935 return compiler_genexp(c, e);
3936 case ListComp_kind:
3937 return compiler_listcomp(c, e);
3938 case SetComp_kind:
3939 return compiler_setcomp(c, e);
3940 case DictComp_kind:
3941 return compiler_dictcomp(c, e);
3942 case Yield_kind:
3943 if (c->u->u_ste->ste_type != FunctionBlock)
3944 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003945 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3946 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003947 if (e->v.Yield.value) {
3948 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 }
3950 else {
3951 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3952 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003953 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003955 case YieldFrom_kind:
3956 if (c->u->u_ste->ste_type != FunctionBlock)
3957 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003958
3959 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3960 return compiler_error(c, "'yield from' inside async function");
3961
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003962 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003963 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003964 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3965 ADDOP(c, YIELD_FROM);
3966 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003967 case Await_kind:
3968 if (c->u->u_ste->ste_type != FunctionBlock)
3969 return compiler_error(c, "'await' outside function");
3970
Yury Selivanov9dec0352015-06-30 12:49:04 -04003971 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3972 return compiler_error(
3973 c, "'await' expressions in comprehensions are not supported");
3974
Yury Selivanov75445082015-05-11 22:57:16 -04003975 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3976 return compiler_error(c, "'await' outside async function");
3977
3978 VISIT(c, expr, e->v.Await.value);
3979 ADDOP(c, GET_AWAITABLE);
3980 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3981 ADDOP(c, YIELD_FROM);
3982 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 case Compare_kind:
3984 return compiler_compare(c, e);
3985 case Call_kind:
3986 return compiler_call(c, e);
3987 case Num_kind:
3988 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3989 break;
3990 case Str_kind:
3991 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3992 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003993 case JoinedStr_kind:
3994 return compiler_joined_str(c, e);
3995 case FormattedValue_kind:
3996 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 case Bytes_kind:
3998 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3999 break;
4000 case Ellipsis_kind:
4001 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4002 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004003 case NameConstant_kind:
4004 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4005 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 /* The following exprs can be assignment targets. */
4007 case Attribute_kind:
4008 if (e->v.Attribute.ctx != AugStore)
4009 VISIT(c, expr, e->v.Attribute.value);
4010 switch (e->v.Attribute.ctx) {
4011 case AugLoad:
4012 ADDOP(c, DUP_TOP);
4013 /* Fall through to load */
4014 case Load:
4015 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4016 break;
4017 case AugStore:
4018 ADDOP(c, ROT_TWO);
4019 /* Fall through to save */
4020 case Store:
4021 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4022 break;
4023 case Del:
4024 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4025 break;
4026 case Param:
4027 default:
4028 PyErr_SetString(PyExc_SystemError,
4029 "param invalid in attribute expression");
4030 return 0;
4031 }
4032 break;
4033 case Subscript_kind:
4034 switch (e->v.Subscript.ctx) {
4035 case AugLoad:
4036 VISIT(c, expr, e->v.Subscript.value);
4037 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4038 break;
4039 case Load:
4040 VISIT(c, expr, e->v.Subscript.value);
4041 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4042 break;
4043 case AugStore:
4044 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4045 break;
4046 case Store:
4047 VISIT(c, expr, e->v.Subscript.value);
4048 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4049 break;
4050 case Del:
4051 VISIT(c, expr, e->v.Subscript.value);
4052 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4053 break;
4054 case Param:
4055 default:
4056 PyErr_SetString(PyExc_SystemError,
4057 "param invalid in subscript expression");
4058 return 0;
4059 }
4060 break;
4061 case Starred_kind:
4062 switch (e->v.Starred.ctx) {
4063 case Store:
4064 /* In all legitimate cases, the Starred node was already replaced
4065 * by compiler_list/compiler_tuple. XXX: is that okay? */
4066 return compiler_error(c,
4067 "starred assignment target must be in a list or tuple");
4068 default:
4069 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004070 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 }
4072 break;
4073 case Name_kind:
4074 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4075 /* child nodes of List and Tuple will have expr_context set */
4076 case List_kind:
4077 return compiler_list(c, e);
4078 case Tuple_kind:
4079 return compiler_tuple(c, e);
4080 }
4081 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082}
4083
4084static int
4085compiler_augassign(struct compiler *c, stmt_ty s)
4086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 expr_ty e = s->v.AugAssign.target;
4088 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 switch (e->kind) {
4093 case Attribute_kind:
4094 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4095 AugLoad, e->lineno, e->col_offset, c->c_arena);
4096 if (auge == NULL)
4097 return 0;
4098 VISIT(c, expr, auge);
4099 VISIT(c, expr, s->v.AugAssign.value);
4100 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4101 auge->v.Attribute.ctx = AugStore;
4102 VISIT(c, expr, auge);
4103 break;
4104 case Subscript_kind:
4105 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4106 AugLoad, e->lineno, e->col_offset, c->c_arena);
4107 if (auge == NULL)
4108 return 0;
4109 VISIT(c, expr, auge);
4110 VISIT(c, expr, s->v.AugAssign.value);
4111 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4112 auge->v.Subscript.ctx = AugStore;
4113 VISIT(c, expr, auge);
4114 break;
4115 case Name_kind:
4116 if (!compiler_nameop(c, e->v.Name.id, Load))
4117 return 0;
4118 VISIT(c, expr, s->v.AugAssign.value);
4119 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4120 return compiler_nameop(c, e->v.Name.id, Store);
4121 default:
4122 PyErr_Format(PyExc_SystemError,
4123 "invalid node type (%d) for augmented assignment",
4124 e->kind);
4125 return 0;
4126 }
4127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128}
4129
4130static int
4131compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 struct fblockinfo *f;
4134 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4135 PyErr_SetString(PyExc_SystemError,
4136 "too many statically nested blocks");
4137 return 0;
4138 }
4139 f = &c->u->u_fblock[c->u->u_nfblocks++];
4140 f->fb_type = t;
4141 f->fb_block = b;
4142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143}
4144
4145static void
4146compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 struct compiler_unit *u = c->u;
4149 assert(u->u_nfblocks > 0);
4150 u->u_nfblocks--;
4151 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4152 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153}
4154
Thomas Wouters89f507f2006-12-13 04:49:30 +00004155static int
4156compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 int i;
4158 struct compiler_unit *u = c->u;
4159 for (i = 0; i < u->u_nfblocks; ++i) {
4160 if (u->u_fblock[i].fb_type == LOOP)
4161 return 1;
4162 }
4163 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004164}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165/* Raises a SyntaxError and returns 0.
4166 If something goes wrong, a different exception may be raised.
4167*/
4168
4169static int
4170compiler_error(struct compiler *c, const char *errstr)
4171{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004172 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174
Victor Stinner14e461d2013-08-26 22:28:21 +02004175 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 if (!loc) {
4177 Py_INCREF(Py_None);
4178 loc = Py_None;
4179 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004180 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004181 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 if (!u)
4183 goto exit;
4184 v = Py_BuildValue("(zO)", errstr, u);
4185 if (!v)
4186 goto exit;
4187 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 Py_DECREF(loc);
4190 Py_XDECREF(u);
4191 Py_XDECREF(v);
4192 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193}
4194
4195static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196compiler_handle_subscr(struct compiler *c, const char *kind,
4197 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 /* XXX this code is duplicated */
4202 switch (ctx) {
4203 case AugLoad: /* fall through to Load */
4204 case Load: op = BINARY_SUBSCR; break;
4205 case AugStore:/* fall through to Store */
4206 case Store: op = STORE_SUBSCR; break;
4207 case Del: op = DELETE_SUBSCR; break;
4208 case Param:
4209 PyErr_Format(PyExc_SystemError,
4210 "invalid %s kind %d in subscript\n",
4211 kind, ctx);
4212 return 0;
4213 }
4214 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004215 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 }
4217 else if (ctx == AugStore) {
4218 ADDOP(c, ROT_THREE);
4219 }
4220 ADDOP(c, op);
4221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222}
4223
4224static int
4225compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 int n = 2;
4228 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 /* only handles the cases where BUILD_SLICE is emitted */
4231 if (s->v.Slice.lower) {
4232 VISIT(c, expr, s->v.Slice.lower);
4233 }
4234 else {
4235 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 if (s->v.Slice.upper) {
4239 VISIT(c, expr, s->v.Slice.upper);
4240 }
4241 else {
4242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4243 }
4244
4245 if (s->v.Slice.step) {
4246 n++;
4247 VISIT(c, expr, s->v.Slice.step);
4248 }
4249 ADDOP_I(c, BUILD_SLICE, n);
4250 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004251}
4252
4253static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4255 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 switch (s->kind) {
4258 case Slice_kind:
4259 return compiler_slice(c, s, ctx);
4260 case Index_kind:
4261 VISIT(c, expr, s->v.Index.value);
4262 break;
4263 case ExtSlice_kind:
4264 default:
4265 PyErr_SetString(PyExc_SystemError,
4266 "extended slice invalid in nested slice");
4267 return 0;
4268 }
4269 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004270}
4271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272static int
4273compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 char * kindname = NULL;
4276 switch (s->kind) {
4277 case Index_kind:
4278 kindname = "index";
4279 if (ctx != AugStore) {
4280 VISIT(c, expr, s->v.Index.value);
4281 }
4282 break;
4283 case Slice_kind:
4284 kindname = "slice";
4285 if (ctx != AugStore) {
4286 if (!compiler_slice(c, s, ctx))
4287 return 0;
4288 }
4289 break;
4290 case ExtSlice_kind:
4291 kindname = "extended slice";
4292 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004293 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 for (i = 0; i < n; i++) {
4295 slice_ty sub = (slice_ty)asdl_seq_GET(
4296 s->v.ExtSlice.dims, i);
4297 if (!compiler_visit_nested_slice(c, sub, ctx))
4298 return 0;
4299 }
4300 ADDOP_I(c, BUILD_TUPLE, n);
4301 }
4302 break;
4303 default:
4304 PyErr_Format(PyExc_SystemError,
4305 "invalid subscript kind %d", s->kind);
4306 return 0;
4307 }
4308 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004309}
4310
Thomas Wouters89f507f2006-12-13 04:49:30 +00004311/* End of the compiler section, beginning of the assembler section */
4312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004313/* do depth-first search of basic block graph, starting with block.
4314 post records the block indices in post-order.
4315
4316 XXX must handle implicit jumps from one block to next
4317*/
4318
Thomas Wouters89f507f2006-12-13 04:49:30 +00004319struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 PyObject *a_bytecode; /* string containing bytecode */
4321 int a_offset; /* offset into bytecode */
4322 int a_nblocks; /* number of reachable blocks */
4323 basicblock **a_postorder; /* list of blocks in dfs postorder */
4324 PyObject *a_lnotab; /* string containing lnotab */
4325 int a_lnotab_off; /* offset into lnotab */
4326 int a_lineno; /* last lineno of emitted instruction */
4327 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004328};
4329
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330static void
4331dfs(struct compiler *c, basicblock *b, struct assembler *a)
4332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 int i;
4334 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 if (b->b_seen)
4337 return;
4338 b->b_seen = 1;
4339 if (b->b_next != NULL)
4340 dfs(c, b->b_next, a);
4341 for (i = 0; i < b->b_iused; i++) {
4342 instr = &b->b_instr[i];
4343 if (instr->i_jrel || instr->i_jabs)
4344 dfs(c, instr->i_target, a);
4345 }
4346 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347}
4348
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004349static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004350stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4351{
Larry Hastings3a907972013-11-23 14:49:22 -08004352 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 struct instr *instr;
4354 if (b->b_seen || b->b_startdepth >= depth)
4355 return maxdepth;
4356 b->b_seen = 1;
4357 b->b_startdepth = depth;
4358 for (i = 0; i < b->b_iused; i++) {
4359 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004360 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4361 if (effect == PY_INVALID_STACK_EFFECT) {
4362 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4363 Py_FatalError("PyCompile_OpcodeStackEffect()");
4364 }
4365 depth += effect;
4366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 if (depth > maxdepth)
4368 maxdepth = depth;
4369 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4370 if (instr->i_jrel || instr->i_jabs) {
4371 target_depth = depth;
4372 if (instr->i_opcode == FOR_ITER) {
4373 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004374 }
4375 else if (instr->i_opcode == SETUP_FINALLY ||
4376 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 target_depth = depth+3;
4378 if (target_depth > maxdepth)
4379 maxdepth = target_depth;
4380 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004381 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4382 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4383 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 maxdepth = stackdepth_walk(c, instr->i_target,
4385 target_depth, maxdepth);
4386 if (instr->i_opcode == JUMP_ABSOLUTE ||
4387 instr->i_opcode == JUMP_FORWARD) {
4388 goto out; /* remaining code is dead */
4389 }
4390 }
4391 }
4392 if (b->b_next)
4393 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 b->b_seen = 0;
4396 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004397}
4398
4399/* Find the flow path that needs the largest stack. We assume that
4400 * cycles in the flow graph have no net effect on the stack depth.
4401 */
4402static int
4403stackdepth(struct compiler *c)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 basicblock *b, *entryblock;
4406 entryblock = NULL;
4407 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4408 b->b_seen = 0;
4409 b->b_startdepth = INT_MIN;
4410 entryblock = b;
4411 }
4412 if (!entryblock)
4413 return 0;
4414 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415}
4416
4417static int
4418assemble_init(struct assembler *a, int nblocks, int firstlineno)
4419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 memset(a, 0, sizeof(struct assembler));
4421 a->a_lineno = firstlineno;
4422 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4423 if (!a->a_bytecode)
4424 return 0;
4425 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4426 if (!a->a_lnotab)
4427 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004428 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 PyErr_NoMemory();
4430 return 0;
4431 }
4432 a->a_postorder = (basicblock **)PyObject_Malloc(
4433 sizeof(basicblock *) * nblocks);
4434 if (!a->a_postorder) {
4435 PyErr_NoMemory();
4436 return 0;
4437 }
4438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004439}
4440
4441static void
4442assemble_free(struct assembler *a)
4443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 Py_XDECREF(a->a_bytecode);
4445 Py_XDECREF(a->a_lnotab);
4446 if (a->a_postorder)
4447 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004448}
4449
4450/* Return the size of a basic block in bytes. */
4451
4452static int
4453instrsize(struct instr *instr)
4454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 if (!instr->i_hasarg)
4456 return 1; /* 1 byte for the opcode*/
4457 if (instr->i_oparg > 0xffff)
4458 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4459 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004460}
4461
4462static int
4463blocksize(basicblock *b)
4464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 int i;
4466 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 for (i = 0; i < b->b_iused; i++)
4469 size += instrsize(&b->b_instr[i]);
4470 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004471}
4472
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004473/* Appends a pair to the end of the line number table, a_lnotab, representing
4474 the instruction's bytecode offset and line number. See
4475 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004476
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004477static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004478assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004481 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 d_bytecode = a->a_offset - a->a_lineno_off;
4485 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 assert(d_bytecode >= 0);
4488 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 if(d_bytecode == 0 && d_lineno == 0)
4491 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (d_bytecode > 255) {
4494 int j, nbytes, ncodes = d_bytecode / 255;
4495 nbytes = a->a_lnotab_off + 2 * ncodes;
4496 len = PyBytes_GET_SIZE(a->a_lnotab);
4497 if (nbytes >= len) {
4498 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4499 len = nbytes;
4500 else if (len <= INT_MAX / 2)
4501 len *= 2;
4502 else {
4503 PyErr_NoMemory();
4504 return 0;
4505 }
4506 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4507 return 0;
4508 }
4509 lnotab = (unsigned char *)
4510 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4511 for (j = 0; j < ncodes; j++) {
4512 *lnotab++ = 255;
4513 *lnotab++ = 0;
4514 }
4515 d_bytecode -= ncodes * 255;
4516 a->a_lnotab_off += ncodes * 2;
4517 }
4518 assert(d_bytecode <= 255);
4519 if (d_lineno > 255) {
4520 int j, nbytes, ncodes = d_lineno / 255;
4521 nbytes = a->a_lnotab_off + 2 * ncodes;
4522 len = PyBytes_GET_SIZE(a->a_lnotab);
4523 if (nbytes >= len) {
4524 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4525 len = nbytes;
4526 else if (len <= INT_MAX / 2)
4527 len *= 2;
4528 else {
4529 PyErr_NoMemory();
4530 return 0;
4531 }
4532 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4533 return 0;
4534 }
4535 lnotab = (unsigned char *)
4536 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4537 *lnotab++ = d_bytecode;
4538 *lnotab++ = 255;
4539 d_bytecode = 0;
4540 for (j = 1; j < ncodes; j++) {
4541 *lnotab++ = 0;
4542 *lnotab++ = 255;
4543 }
4544 d_lineno -= ncodes * 255;
4545 a->a_lnotab_off += ncodes * 2;
4546 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 len = PyBytes_GET_SIZE(a->a_lnotab);
4549 if (a->a_lnotab_off + 2 >= len) {
4550 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4551 return 0;
4552 }
4553 lnotab = (unsigned char *)
4554 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 a->a_lnotab_off += 2;
4557 if (d_bytecode) {
4558 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004559 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 }
4561 else { /* First line of a block; def stmt, etc. */
4562 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004563 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 }
4565 a->a_lineno = i->i_lineno;
4566 a->a_lineno_off = a->a_offset;
4567 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004568}
4569
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004570/* assemble_emit()
4571 Extend the bytecode with a new instruction.
4572 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004573*/
4574
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004575static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004576assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 int size, arg = 0, ext = 0;
4579 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4580 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 size = instrsize(i);
4583 if (i->i_hasarg) {
4584 arg = i->i_oparg;
4585 ext = arg >> 16;
4586 }
4587 if (i->i_lineno && !assemble_lnotab(a, i))
4588 return 0;
4589 if (a->a_offset + size >= len) {
4590 if (len > PY_SSIZE_T_MAX / 2)
4591 return 0;
4592 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4593 return 0;
4594 }
4595 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4596 a->a_offset += size;
4597 if (size == 6) {
4598 assert(i->i_hasarg);
4599 *code++ = (char)EXTENDED_ARG;
4600 *code++ = ext & 0xff;
4601 *code++ = ext >> 8;
4602 arg &= 0xffff;
4603 }
4604 *code++ = i->i_opcode;
4605 if (i->i_hasarg) {
4606 assert(size == 3 || size == 6);
4607 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004608 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 }
4610 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004611}
4612
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004613static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004614assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 basicblock *b;
4617 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4618 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 /* Compute the size of each block and fixup jump args.
4621 Replace block pointer with position in bytecode. */
4622 do {
4623 totsize = 0;
4624 for (i = a->a_nblocks - 1; i >= 0; i--) {
4625 b = a->a_postorder[i];
4626 bsize = blocksize(b);
4627 b->b_offset = totsize;
4628 totsize += bsize;
4629 }
4630 last_extended_arg_count = extended_arg_count;
4631 extended_arg_count = 0;
4632 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4633 bsize = b->b_offset;
4634 for (i = 0; i < b->b_iused; i++) {
4635 struct instr *instr = &b->b_instr[i];
4636 /* Relative jumps are computed relative to
4637 the instruction pointer after fetching
4638 the jump instruction.
4639 */
4640 bsize += instrsize(instr);
4641 if (instr->i_jabs)
4642 instr->i_oparg = instr->i_target->b_offset;
4643 else if (instr->i_jrel) {
4644 int delta = instr->i_target->b_offset - bsize;
4645 instr->i_oparg = delta;
4646 }
4647 else
4648 continue;
4649 if (instr->i_oparg > 0xffff)
4650 extended_arg_count++;
4651 }
4652 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 /* XXX: This is an awful hack that could hurt performance, but
4655 on the bright side it should work until we come up
4656 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 The issue is that in the first loop blocksize() is called
4659 which calls instrsize() which requires i_oparg be set
4660 appropriately. There is a bootstrap problem because
4661 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 So we loop until we stop seeing new EXTENDED_ARGs.
4664 The only EXTENDED_ARGs that could be popping up are
4665 ones in jump instructions. So this should converge
4666 fairly quickly.
4667 */
4668 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004669}
4670
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004671static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004672dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 PyObject *tuple, *k, *v;
4675 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 tuple = PyTuple_New(size);
4678 if (tuple == NULL)
4679 return NULL;
4680 while (PyDict_Next(dict, &pos, &k, &v)) {
4681 i = PyLong_AS_LONG(v);
4682 /* The keys of the dictionary are tuples. (see compiler_add_o)
4683 The object we want is always first, though. */
4684 k = PyTuple_GET_ITEM(k, 0);
4685 Py_INCREF(k);
4686 assert((i - offset) < size);
4687 assert((i - offset) >= 0);
4688 PyTuple_SET_ITEM(tuple, i - offset, k);
4689 }
4690 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004691}
4692
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004694compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004697 int flags = 0;
4698 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004700 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 if (ste->ste_nested)
4702 flags |= CO_NESTED;
4703 if (ste->ste_generator)
4704 flags |= CO_GENERATOR;
4705 if (ste->ste_varargs)
4706 flags |= CO_VARARGS;
4707 if (ste->ste_varkeywords)
4708 flags |= CO_VARKEYWORDS;
4709 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 /* (Only) inherit compilerflags in PyCF_MASK */
4712 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 n = PyDict_Size(c->u->u_freevars);
4715 if (n < 0)
4716 return -1;
4717 if (n == 0) {
4718 n = PyDict_Size(c->u->u_cellvars);
4719 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004720 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004722 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 }
4724 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004727}
4728
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004729static PyCodeObject *
4730makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 PyObject *tmp;
4733 PyCodeObject *co = NULL;
4734 PyObject *consts = NULL;
4735 PyObject *names = NULL;
4736 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 PyObject *name = NULL;
4738 PyObject *freevars = NULL;
4739 PyObject *cellvars = NULL;
4740 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004741 Py_ssize_t nlocals;
4742 int nlocals_int;
4743 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004744 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 tmp = dict_keys_inorder(c->u->u_consts, 0);
4747 if (!tmp)
4748 goto error;
4749 consts = PySequence_List(tmp); /* optimize_code requires a list */
4750 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 names = dict_keys_inorder(c->u->u_names, 0);
4753 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4754 if (!consts || !names || !varnames)
4755 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4758 if (!cellvars)
4759 goto error;
4760 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4761 if (!freevars)
4762 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004765 assert(nlocals < INT_MAX);
4766 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 flags = compute_code_flags(c);
4769 if (flags < 0)
4770 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4773 if (!bytecode)
4774 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4777 if (!tmp)
4778 goto error;
4779 Py_DECREF(consts);
4780 consts = tmp;
4781
Victor Stinnerf8e32212013-11-19 23:56:34 +01004782 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4783 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4784 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004785 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 bytecode, consts, names, varnames,
4787 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004788 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 c->u->u_firstlineno,
4790 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004791 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 Py_XDECREF(consts);
4793 Py_XDECREF(names);
4794 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 Py_XDECREF(name);
4796 Py_XDECREF(freevars);
4797 Py_XDECREF(cellvars);
4798 Py_XDECREF(bytecode);
4799 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004800}
4801
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004802
4803/* For debugging purposes only */
4804#if 0
4805static void
4806dump_instr(const struct instr *i)
4807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 const char *jrel = i->i_jrel ? "jrel " : "";
4809 const char *jabs = i->i_jabs ? "jabs " : "";
4810 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 *arg = '\0';
4813 if (i->i_hasarg)
4814 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4817 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004818}
4819
4820static void
4821dump_basicblock(const basicblock *b)
4822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 const char *seen = b->b_seen ? "seen " : "";
4824 const char *b_return = b->b_return ? "return " : "";
4825 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4826 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4827 if (b->b_instr) {
4828 int i;
4829 for (i = 0; i < b->b_iused; i++) {
4830 fprintf(stderr, " [%02d] ", i);
4831 dump_instr(b->b_instr + i);
4832 }
4833 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004834}
4835#endif
4836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004837static PyCodeObject *
4838assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 basicblock *b, *entryblock;
4841 struct assembler a;
4842 int i, j, nblocks;
4843 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 /* Make sure every block that falls off the end returns None.
4846 XXX NEXT_BLOCK() isn't quite right, because if the last
4847 block ends with a jump or return b_next shouldn't set.
4848 */
4849 if (!c->u->u_curblock->b_return) {
4850 NEXT_BLOCK(c);
4851 if (addNone)
4852 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4853 ADDOP(c, RETURN_VALUE);
4854 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 nblocks = 0;
4857 entryblock = NULL;
4858 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4859 nblocks++;
4860 entryblock = b;
4861 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 /* Set firstlineno if it wasn't explicitly set. */
4864 if (!c->u->u_firstlineno) {
4865 if (entryblock && entryblock->b_instr)
4866 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4867 else
4868 c->u->u_firstlineno = 1;
4869 }
4870 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4871 goto error;
4872 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 /* Can't modify the bytecode after computing jump offsets. */
4875 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 /* Emit code in reverse postorder from dfs. */
4878 for (i = a.a_nblocks - 1; i >= 0; i--) {
4879 b = a.a_postorder[i];
4880 for (j = 0; j < b->b_iused; j++)
4881 if (!assemble_emit(&a, &b->b_instr[j]))
4882 goto error;
4883 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4886 goto error;
4887 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4888 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 assemble_free(&a);
4893 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004894}
Georg Brandl8334fd92010-12-04 10:26:46 +00004895
4896#undef PyAST_Compile
4897PyAPI_FUNC(PyCodeObject *)
4898PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4899 PyArena *arena)
4900{
4901 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4902}