blob: faae4f5828f8ffde7296d03203e574b34910744e [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"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 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 int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static 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 Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int 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);
Victor Stinnerefb24132016-01-22 12:33:12 +0100396 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 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++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100459 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 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) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700480 assert((uintptr_t)block != 0xcbcbcbcbU);
481 assert((uintptr_t)block != 0xfbfbfbfbU);
482 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 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;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100526 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
529 struct compiler_unit));
530 if (!u) {
531 PyErr_NoMemory();
532 return 0;
533 }
534 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100535 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 u->u_argcount = 0;
537 u->u_kwonlyargcount = 0;
538 u->u_ste = PySymtable_Lookup(c->c_st, key);
539 if (!u->u_ste) {
540 compiler_unit_free(u);
541 return 0;
542 }
543 Py_INCREF(name);
544 u->u_name = name;
545 u->u_varnames = list2dict(u->u_ste->ste_varnames);
546 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
547 if (!u->u_varnames || !u->u_cellvars) {
548 compiler_unit_free(u);
549 return 0;
550 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500551 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000552 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500553 _Py_IDENTIFIER(__class__);
554 PyObject *tuple, *name, *zero;
555 int res;
556 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
557 assert(PyDict_Size(u->u_cellvars) == 0);
558 name = _PyUnicode_FromId(&PyId___class__);
559 if (!name) {
560 compiler_unit_free(u);
561 return 0;
562 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100563 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500564 if (!tuple) {
565 compiler_unit_free(u);
566 return 0;
567 }
568 zero = PyLong_FromLong(0);
569 if (!zero) {
570 Py_DECREF(tuple);
571 compiler_unit_free(u);
572 return 0;
573 }
574 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
575 Py_DECREF(tuple);
576 Py_DECREF(zero);
577 if (res < 0) {
578 compiler_unit_free(u);
579 return 0;
580 }
581 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
584 PyDict_Size(u->u_cellvars));
585 if (!u->u_freevars) {
586 compiler_unit_free(u);
587 return 0;
588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_blocks = NULL;
591 u->u_nfblocks = 0;
592 u->u_firstlineno = lineno;
593 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000594 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_lineno_set = 0;
596 u->u_consts = PyDict_New();
597 if (!u->u_consts) {
598 compiler_unit_free(u);
599 return 0;
600 }
601 u->u_names = PyDict_New();
602 if (!u->u_names) {
603 compiler_unit_free(u);
604 return 0;
605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Push the old compiler_unit on the stack. */
610 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400611 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
613 Py_XDECREF(capsule);
614 compiler_unit_free(u);
615 return 0;
616 }
617 Py_DECREF(capsule);
618 u->u_private = c->u->u_private;
619 Py_XINCREF(u->u_private);
620 }
621 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100624
625 block = compiler_new_block(c);
626 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100628 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400630 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
631 if (!compiler_set_qualname(c))
632 return 0;
633 }
634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636}
637
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000638static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639compiler_exit_scope(struct compiler *c)
640{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100641 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 c->c_nestlevel--;
645 compiler_unit_free(c->u);
646 /* Restore c->u to the parent unit. */
647 n = PyList_GET_SIZE(c->c_stack) - 1;
648 if (n >= 0) {
649 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400650 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 assert(c->u);
652 /* we are deleting from a list so this really shouldn't fail */
653 if (PySequence_DelItem(c->c_stack, n) < 0)
654 Py_FatalError("compiler_exit_scope()");
655 compiler_unit_check(c->u);
656 }
657 else
658 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660}
661
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400662static int
663compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100665 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666 _Py_static_string(dot_locals, ".<locals>");
667 Py_ssize_t stack_size;
668 struct compiler_unit *u = c->u;
669 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100670
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100672 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400673 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 if (stack_size > 1) {
675 int scope, force_global = 0;
676 struct compiler_unit *parent;
677 PyObject *mangled, *capsule;
678
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400679 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400680 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 assert(parent);
682
Yury Selivanov75445082015-05-11 22:57:16 -0400683 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
684 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
685 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 assert(u->u_name);
687 mangled = _Py_Mangle(parent->u_private, u->u_name);
688 if (!mangled)
689 return 0;
690 scope = PyST_GetScope(parent->u_ste, mangled);
691 Py_DECREF(mangled);
692 assert(scope != GLOBAL_IMPLICIT);
693 if (scope == GLOBAL_EXPLICIT)
694 force_global = 1;
695 }
696
697 if (!force_global) {
698 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400699 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
701 dot_locals_str = _PyUnicode_FromId(&dot_locals);
702 if (dot_locals_str == NULL)
703 return 0;
704 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
705 if (base == NULL)
706 return 0;
707 }
708 else {
709 Py_INCREF(parent->u_qualname);
710 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400711 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100712 }
713 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 if (base != NULL) {
716 dot_str = _PyUnicode_FromId(&dot);
717 if (dot_str == NULL) {
718 Py_DECREF(base);
719 return 0;
720 }
721 name = PyUnicode_Concat(base, dot_str);
722 Py_DECREF(base);
723 if (name == NULL)
724 return 0;
725 PyUnicode_Append(&name, u->u_name);
726 if (name == NULL)
727 return 0;
728 }
729 else {
730 Py_INCREF(u->u_name);
731 name = u->u_name;
732 }
733 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100734
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400735 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100736}
737
Eric V. Smith235a6f02015-09-19 14:51:32 -0400738
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000739/* Allocate a new block and return a pointer to it.
740 Returns NULL on error.
741*/
742
743static basicblock *
744compiler_new_block(struct compiler *c)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 basicblock *b;
747 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 u = c->u;
750 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
751 if (b == NULL) {
752 PyErr_NoMemory();
753 return NULL;
754 }
755 memset((void *)b, 0, sizeof(basicblock));
756 /* Extend the singly linked list of blocks with new block. */
757 b->b_list = u->u_blocks;
758 u->u_blocks = b;
759 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760}
761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763compiler_next_block(struct compiler *c)
764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 basicblock *block = compiler_new_block(c);
766 if (block == NULL)
767 return NULL;
768 c->u->u_curblock->b_next = block;
769 c->u->u_curblock = block;
770 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771}
772
773static basicblock *
774compiler_use_next_block(struct compiler *c, basicblock *block)
775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 assert(block != NULL);
777 c->u->u_curblock->b_next = block;
778 c->u->u_curblock = block;
779 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780}
781
782/* Returns the offset of the next instruction in the current block's
783 b_instr array. Resizes the b_instr as necessary.
784 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000785*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786
787static int
788compiler_next_instr(struct compiler *c, basicblock *b)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 assert(b != NULL);
791 if (b->b_instr == NULL) {
792 b->b_instr = (struct instr *)PyObject_Malloc(
793 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
794 if (b->b_instr == NULL) {
795 PyErr_NoMemory();
796 return -1;
797 }
798 b->b_ialloc = DEFAULT_BLOCK_SIZE;
799 memset((char *)b->b_instr, 0,
800 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
801 }
802 else if (b->b_iused == b->b_ialloc) {
803 struct instr *tmp;
804 size_t oldsize, newsize;
805 oldsize = b->b_ialloc * sizeof(struct instr);
806 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000807
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700808 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyErr_NoMemory();
810 return -1;
811 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (newsize == 0) {
814 PyErr_NoMemory();
815 return -1;
816 }
817 b->b_ialloc <<= 1;
818 tmp = (struct instr *)PyObject_Realloc(
819 (void *)b->b_instr, newsize);
820 if (tmp == NULL) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_instr = tmp;
825 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
826 }
827 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000828}
829
Christian Heimes2202f872008-02-06 14:31:34 +0000830/* Set the i_lineno member of the instruction at offset off if the
831 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000832 already been set. If it has been set, the call has no effect.
833
Christian Heimes2202f872008-02-06 14:31:34 +0000834 The line number is reset in the following cases:
835 - when entering a new scope
836 - on each statement
837 - on each expression that start a new line
838 - before the "except" clause
839 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842static void
843compiler_set_lineno(struct compiler *c, int off)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 basicblock *b;
846 if (c->u->u_lineno_set)
847 return;
848 c->u->u_lineno_set = 1;
849 b = c->u->u_curblock;
850 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851}
852
Larry Hastings3a907972013-11-23 14:49:22 -0800853int
854PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 switch (opcode) {
857 case POP_TOP:
858 return -1;
859 case ROT_TWO:
860 case ROT_THREE:
861 return 0;
862 case DUP_TOP:
863 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000864 case DUP_TOP_TWO:
865 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 case UNARY_POSITIVE:
868 case UNARY_NEGATIVE:
869 case UNARY_NOT:
870 case UNARY_INVERT:
871 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 case SET_ADD:
874 case LIST_APPEND:
875 return -1;
876 case MAP_ADD:
877 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 case BINARY_POWER:
880 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400881 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_MODULO:
883 case BINARY_ADD:
884 case BINARY_SUBTRACT:
885 case BINARY_SUBSCR:
886 case BINARY_FLOOR_DIVIDE:
887 case BINARY_TRUE_DIVIDE:
888 return -1;
889 case INPLACE_FLOOR_DIVIDE:
890 case INPLACE_TRUE_DIVIDE:
891 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case INPLACE_ADD:
894 case INPLACE_SUBTRACT:
895 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400896 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 case INPLACE_MODULO:
898 return -1;
899 case STORE_SUBSCR:
900 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case DELETE_SUBSCR:
902 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case BINARY_LSHIFT:
905 case BINARY_RSHIFT:
906 case BINARY_AND:
907 case BINARY_XOR:
908 case BINARY_OR:
909 return -1;
910 case INPLACE_POWER:
911 return -1;
912 case GET_ITER:
913 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case PRINT_EXPR:
916 return -1;
917 case LOAD_BUILD_CLASS:
918 return 1;
919 case INPLACE_LSHIFT:
920 case INPLACE_RSHIFT:
921 case INPLACE_AND:
922 case INPLACE_XOR:
923 case INPLACE_OR:
924 return -1;
925 case BREAK_LOOP:
926 return 0;
927 case SETUP_WITH:
928 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400929 case WITH_CLEANUP_START:
930 return 1;
931 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case RETURN_VALUE:
934 return -1;
935 case IMPORT_STAR:
936 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700937 case SETUP_ANNOTATIONS:
938 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case YIELD_VALUE:
940 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500941 case YIELD_FROM:
942 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case POP_BLOCK:
944 return 0;
945 case POP_EXCEPT:
946 return 0; /* -3 except if bad bytecode */
947 case END_FINALLY:
948 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case STORE_NAME:
951 return -1;
952 case DELETE_NAME:
953 return 0;
954 case UNPACK_SEQUENCE:
955 return oparg-1;
956 case UNPACK_EX:
957 return (oparg&0xFF) + (oparg>>8);
958 case FOR_ITER:
959 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case STORE_ATTR:
962 return -2;
963 case DELETE_ATTR:
964 return -1;
965 case STORE_GLOBAL:
966 return -1;
967 case DELETE_GLOBAL:
968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case LOAD_CONST:
970 return 1;
971 case LOAD_NAME:
972 return 1;
973 case BUILD_TUPLE:
974 case BUILD_LIST:
975 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300976 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400978 case BUILD_LIST_UNPACK:
979 case BUILD_TUPLE_UNPACK:
980 case BUILD_SET_UNPACK:
981 case BUILD_MAP_UNPACK:
982 return 1 - oparg;
983 case BUILD_MAP_UNPACK_WITH_CALL:
984 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700986 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300987 case BUILD_CONST_KEY_MAP:
988 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case LOAD_ATTR:
990 return 0;
991 case COMPARE_OP:
992 return -1;
993 case IMPORT_NAME:
994 return -1;
995 case IMPORT_FROM:
996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case JUMP_FORWARD:
999 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1000 case JUMP_IF_FALSE_OR_POP: /* "" */
1001 case JUMP_ABSOLUTE:
1002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case POP_JUMP_IF_FALSE:
1005 case POP_JUMP_IF_TRUE:
1006 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_GLOBAL:
1009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case CONTINUE_LOOP:
1012 return 0;
1013 case SETUP_LOOP:
1014 return 0;
1015 case SETUP_EXCEPT:
1016 case SETUP_FINALLY:
1017 return 6; /* can push 3 values for the new exception
1018 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_FAST:
1021 return 1;
1022 case STORE_FAST:
1023 return -1;
1024 case DELETE_FAST:
1025 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001026 case STORE_ANNOTATION:
1027 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case RAISE_VARARGS:
1030 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001031#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case CALL_FUNCTION:
1033 return -NARGS(oparg);
1034 case CALL_FUNCTION_VAR:
1035 case CALL_FUNCTION_KW:
1036 return -NARGS(oparg)-1;
1037 case CALL_FUNCTION_VAR_KW:
1038 return -NARGS(oparg)-2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001039#undef NARGS
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001040 case MAKE_FUNCTION:
1041 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1042 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
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;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001070 case FORMAT_VALUE:
1071 /* If there's a fmt_spec on the stack, we go from 2->1,
1072 else 1->1. */
1073 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001075 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 }
Larry Hastings3a907972013-11-23 14:49:22 -08001077 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
1080/* Add an opcode with no argument.
1081 Returns 0 on failure, 1 on success.
1082*/
1083
1084static int
1085compiler_addop(struct compiler *c, int opcode)
1086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 basicblock *b;
1088 struct instr *i;
1089 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001090 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 off = compiler_next_instr(c, c->u->u_curblock);
1092 if (off < 0)
1093 return 0;
1094 b = c->u->u_curblock;
1095 i = &b->b_instr[off];
1096 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001097 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (opcode == RETURN_VALUE)
1099 b->b_return = 1;
1100 compiler_set_lineno(c, off);
1101 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102}
1103
Victor Stinnerf8e32212013-11-19 23:56:34 +01001104static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyObject *t, *v;
1108 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109
Victor Stinnerefb24132016-01-22 12:33:12 +01001110 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (t == NULL)
1112 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 v = PyDict_GetItem(dict, t);
1115 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001116 if (PyErr_Occurred()) {
1117 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001121 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (!v) {
1123 Py_DECREF(t);
1124 return -1;
1125 }
1126 if (PyDict_SetItem(dict, t, v) < 0) {
1127 Py_DECREF(t);
1128 Py_DECREF(v);
1129 return -1;
1130 }
1131 Py_DECREF(v);
1132 }
1133 else
1134 arg = PyLong_AsLong(v);
1135 Py_DECREF(t);
1136 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137}
1138
1139static int
1140compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001143 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001145 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 return compiler_addop_i(c, opcode, arg);
1147}
1148
1149static int
1150compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001153 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1155 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 arg = compiler_add_o(c, dict, mangled);
1158 Py_DECREF(mangled);
1159 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 return compiler_addop_i(c, opcode, arg);
1162}
1163
1164/* Add an opcode with an integer argument.
1165 Returns 0 on failure, 1 on success.
1166*/
1167
1168static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001169compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 struct instr *i;
1172 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001173
Victor Stinner2ad474b2016-03-01 23:34:47 +01001174 /* oparg value is unsigned, but a signed C int is usually used to store
1175 it in the C code (like Python/ceval.c).
1176
1177 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1178
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001179 The argument of a concrete bytecode instruction is limited to 8-bit.
1180 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1181 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001182 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 off = compiler_next_instr(c, c->u->u_curblock);
1185 if (off < 0)
1186 return 0;
1187 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001188 i->i_opcode = opcode;
1189 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 compiler_set_lineno(c, off);
1191 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192}
1193
1194static int
1195compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 struct instr *i;
1198 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001200 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 assert(b != NULL);
1202 off = compiler_next_instr(c, c->u->u_curblock);
1203 if (off < 0)
1204 return 0;
1205 i = &c->u->u_curblock->b_instr[off];
1206 i->i_opcode = opcode;
1207 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (absolute)
1209 i->i_jabs = 1;
1210 else
1211 i->i_jrel = 1;
1212 compiler_set_lineno(c, off);
1213 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001216/* NEXT_BLOCK() creates an implicit jump from the current block
1217 to the new block.
1218
1219 The returns inside this macro make it impossible to decref objects
1220 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (compiler_next_block((C)) == NULL) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
1227#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!compiler_addop((C), (OP))) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001232#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (!compiler_addop((C), (OP))) { \
1234 compiler_exit_scope(c); \
1235 return 0; \
1236 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001237}
1238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1241 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242}
1243
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001244/* Same as ADDOP_O, but steals a reference. */
1245#define ADDOP_N(C, OP, O, TYPE) { \
1246 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1247 Py_DECREF((O)); \
1248 return 0; \
1249 } \
1250 Py_DECREF((O)); \
1251}
1252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1255 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256}
1257
1258#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_i((C), (OP), (O))) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_j((C), (OP), (O), 1)) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_addop_j((C), (OP), (O), 0)) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1274 the ASDL name to synthesize the name of the C type and the visit function.
1275*/
1276
1277#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!compiler_visit_ ## TYPE((C), (V))) \
1279 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280}
1281
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001282#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (!compiler_visit_ ## TYPE((C), (V))) { \
1284 compiler_exit_scope(c); \
1285 return 0; \
1286 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001287}
1288
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_visit_slice((C), (V), (CTX))) \
1291 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292}
1293
1294#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 int _i; \
1296 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1297 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1298 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1299 if (!compiler_visit_ ## TYPE((C), elt)) \
1300 return 0; \
1301 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302}
1303
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001304#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int _i; \
1306 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1307 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1308 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1309 if (!compiler_visit_ ## TYPE((C), elt)) { \
1310 compiler_exit_scope(c); \
1311 return 0; \
1312 } \
1313 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001314}
1315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316static int
1317compiler_isdocstring(stmt_ty s)
1318{
1319 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001320 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001321 if (s->v.Expr.value->kind == Str_kind)
1322 return 1;
1323 if (s->v.Expr.value->kind == Constant_kind)
1324 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326}
1327
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001328static int
1329is_const(expr_ty e)
1330{
1331 switch (e->kind) {
1332 case Constant_kind:
1333 case Num_kind:
1334 case Str_kind:
1335 case Bytes_kind:
1336 case Ellipsis_kind:
1337 case NameConstant_kind:
1338 return 1;
1339 default:
1340 return 0;
1341 }
1342}
1343
1344static PyObject *
1345get_const_value(expr_ty e)
1346{
1347 switch (e->kind) {
1348 case Constant_kind:
1349 return e->v.Constant.value;
1350 case Num_kind:
1351 return e->v.Num.n;
1352 case Str_kind:
1353 return e->v.Str.s;
1354 case Bytes_kind:
1355 return e->v.Bytes.s;
1356 case Ellipsis_kind:
1357 return Py_Ellipsis;
1358 case NameConstant_kind:
1359 return e->v.NameConstant.value;
1360 default:
1361 assert(!is_const(e));
1362 return NULL;
1363 }
1364}
1365
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001366/* Search if variable annotations are present statically in a block. */
1367
1368static int
1369find_ann(asdl_seq *stmts)
1370{
1371 int i, j, res = 0;
1372 stmt_ty st;
1373
1374 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1375 st = (stmt_ty)asdl_seq_GET(stmts, i);
1376 switch (st->kind) {
1377 case AnnAssign_kind:
1378 return 1;
1379 case For_kind:
1380 res = find_ann(st->v.For.body) ||
1381 find_ann(st->v.For.orelse);
1382 break;
1383 case AsyncFor_kind:
1384 res = find_ann(st->v.AsyncFor.body) ||
1385 find_ann(st->v.AsyncFor.orelse);
1386 break;
1387 case While_kind:
1388 res = find_ann(st->v.While.body) ||
1389 find_ann(st->v.While.orelse);
1390 break;
1391 case If_kind:
1392 res = find_ann(st->v.If.body) ||
1393 find_ann(st->v.If.orelse);
1394 break;
1395 case With_kind:
1396 res = find_ann(st->v.With.body);
1397 break;
1398 case AsyncWith_kind:
1399 res = find_ann(st->v.AsyncWith.body);
1400 break;
1401 case Try_kind:
1402 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1403 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1404 st->v.Try.handlers, j);
1405 if (find_ann(handler->v.ExceptHandler.body)) {
1406 return 1;
1407 }
1408 }
1409 res = find_ann(st->v.Try.body) ||
1410 find_ann(st->v.Try.finalbody) ||
1411 find_ann(st->v.Try.orelse);
1412 break;
1413 default:
1414 res = 0;
1415 }
1416 if (res) {
1417 break;
1418 }
1419 }
1420 return res;
1421}
1422
1423/* Compile a sequence of statements, checking for a docstring
1424 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425
1426static int
1427compiler_body(struct compiler *c, asdl_seq *stmts)
1428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 int i = 0;
1430 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001432 /* Set current line number to the line number of first statement.
1433 This way line number for SETUP_ANNOTATIONS will always
1434 coincide with the line number of first "real" statement in module.
1435 If body is empy, then lineno will be set later in assemble. */
1436 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1437 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
1438 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1439 c->u->u_lineno = st->lineno;
1440 }
1441 /* Every annotated class and module should have __annotations__. */
1442 if (find_ann(stmts)) {
1443 ADDOP(c, SETUP_ANNOTATIONS);
1444 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (!asdl_seq_LEN(stmts))
1446 return 1;
1447 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001448 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* don't generate docstrings if -OO */
1450 i = 1;
1451 VISIT(c, expr, st->v.Expr.value);
1452 if (!compiler_nameop(c, __doc__, Store))
1453 return 0;
1454 }
1455 for (; i < asdl_seq_LEN(stmts); i++)
1456 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1457 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458}
1459
1460static PyCodeObject *
1461compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyCodeObject *co;
1464 int addNone = 1;
1465 static PyObject *module;
1466 if (!module) {
1467 module = PyUnicode_InternFromString("<module>");
1468 if (!module)
1469 return NULL;
1470 }
1471 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001472 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 return NULL;
1474 switch (mod->kind) {
1475 case Module_kind:
1476 if (!compiler_body(c, mod->v.Module.body)) {
1477 compiler_exit_scope(c);
1478 return 0;
1479 }
1480 break;
1481 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001482 if (find_ann(mod->v.Interactive.body)) {
1483 ADDOP(c, SETUP_ANNOTATIONS);
1484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 c->c_interactive = 1;
1486 VISIT_SEQ_IN_SCOPE(c, stmt,
1487 mod->v.Interactive.body);
1488 break;
1489 case Expression_kind:
1490 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1491 addNone = 0;
1492 break;
1493 case Suite_kind:
1494 PyErr_SetString(PyExc_SystemError,
1495 "suite should not be possible");
1496 return 0;
1497 default:
1498 PyErr_Format(PyExc_SystemError,
1499 "module kind %d should not be possible",
1500 mod->kind);
1501 return 0;
1502 }
1503 co = assemble(c, addNone);
1504 compiler_exit_scope(c);
1505 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001506}
1507
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508/* The test for LOCAL must come before the test for FREE in order to
1509 handle classes where name is both local and free. The local var is
1510 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001511*/
1512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513static int
1514get_ref_type(struct compiler *c, PyObject *name)
1515{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001516 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001517 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1518 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1519 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001520 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (scope == 0) {
1522 char buf[350];
1523 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001524 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001526 PyUnicode_AsUTF8(name),
1527 PyUnicode_AsUTF8(c->u->u_name),
1528 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1529 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1530 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1531 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 );
1533 Py_FatalError(buf);
1534 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537}
1538
1539static int
1540compiler_lookup_arg(PyObject *dict, PyObject *name)
1541{
1542 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001543 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001545 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001547 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001549 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001550 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551}
1552
1553static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001554compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001556 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001557 if (qualname == NULL)
1558 qualname = co->co_name;
1559
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001560 if (free) {
1561 for (i = 0; i < free; ++i) {
1562 /* Bypass com_addop_varname because it will generate
1563 LOAD_DEREF but LOAD_CLOSURE is needed.
1564 */
1565 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1566 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001568 /* Special case: If a class contains a method with a
1569 free variable that has the same name as a method,
1570 the name will be considered free *and* local in the
1571 class. It should be handled by the closure, as
1572 well as by the normal name loookup logic.
1573 */
1574 reftype = get_ref_type(c, name);
1575 if (reftype == CELL)
1576 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1577 else /* (reftype == FREE) */
1578 arg = compiler_lookup_arg(c->u->u_freevars, name);
1579 if (arg == -1) {
1580 fprintf(stderr,
1581 "lookup %s in %s %d %d\n"
1582 "freevars of %s: %s\n",
1583 PyUnicode_AsUTF8(PyObject_Repr(name)),
1584 PyUnicode_AsUTF8(c->u->u_name),
1585 reftype, arg,
1586 PyUnicode_AsUTF8(co->co_name),
1587 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1588 Py_FatalError("compiler_make_closure()");
1589 }
1590 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001592 flags |= 0x08;
1593 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001596 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001597 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599}
1600
1601static int
1602compiler_decorators(struct compiler *c, asdl_seq* decos)
1603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (!decos)
1607 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1610 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1611 }
1612 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613}
1614
1615static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001616compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001618{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001619 /* Push a dict of keyword-only default values.
1620
1621 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1622 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001623 int i;
1624 PyObject *keys = NULL;
1625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1627 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1628 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1629 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001630 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001631 if (!mangled) {
1632 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001634 if (keys == NULL) {
1635 keys = PyList_New(1);
1636 if (keys == NULL) {
1637 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001638 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001639 }
1640 PyList_SET_ITEM(keys, 0, mangled);
1641 }
1642 else {
1643 int res = PyList_Append(keys, mangled);
1644 Py_DECREF(mangled);
1645 if (res == -1) {
1646 goto error;
1647 }
1648 }
1649 if (!compiler_visit_expr(c, default_)) {
1650 goto error;
1651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 }
1653 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001654 if (keys != NULL) {
1655 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1656 PyObject *keys_tuple = PyList_AsTuple(keys);
1657 Py_DECREF(keys);
1658 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001659 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001660 }
1661 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1662 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001663 assert(default_count > 0);
1664 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001665 }
1666 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001667 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001668 }
1669
1670error:
1671 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001672 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001673}
1674
1675static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001676compiler_visit_argannotation(struct compiler *c, identifier id,
1677 expr_ty annotation, PyObject *names)
1678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001680 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001682 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001683 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001684 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001685 if (PyList_Append(names, mangled) < 0) {
1686 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001687 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001688 }
1689 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001692}
1693
1694static int
1695compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1696 PyObject *names)
1697{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001698 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 for (i = 0; i < asdl_seq_LEN(args); i++) {
1700 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001701 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 c,
1703 arg->arg,
1704 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001705 names))
1706 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001708 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001709}
1710
1711static int
1712compiler_visit_annotations(struct compiler *c, arguments_ty args,
1713 expr_ty returns)
1714{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001715 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001716 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001717
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001718 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 */
1720 static identifier return_str;
1721 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001722 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 names = PyList_New(0);
1724 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001725 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001726
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001727 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001729 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001730 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001731 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001733 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001735 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001736 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001737 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (!return_str) {
1741 return_str = PyUnicode_InternFromString("return");
1742 if (!return_str)
1743 goto error;
1744 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001745 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 goto error;
1747 }
1748
1749 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001751 PyObject *keytuple = PyList_AsTuple(names);
1752 Py_DECREF(names);
1753 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001754 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001756 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1757 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001758 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001760 else {
1761 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001762 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001763 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001764
1765error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001767 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001768}
1769
1770static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771compiler_visit_defaults(struct compiler *c, arguments_ty args)
1772{
1773 VISIT_SEQ(c, expr, args->defaults);
1774 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1775 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776}
1777
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001778static Py_ssize_t
1779compiler_default_arguments(struct compiler *c, arguments_ty args)
1780{
1781 Py_ssize_t funcflags = 0;
1782 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001783 if (!compiler_visit_defaults(c, args))
1784 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001785 funcflags |= 0x01;
1786 }
1787 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001788 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001789 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001790 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001791 return -1;
1792 }
1793 else if (res > 0) {
1794 funcflags |= 0x02;
1795 }
1796 }
1797 return funcflags;
1798}
1799
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800static int
Yury Selivanov75445082015-05-11 22:57:16 -04001801compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001804 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001805 arguments_ty args;
1806 expr_ty returns;
1807 identifier name;
1808 asdl_seq* decos;
1809 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 Py_ssize_t i, n, funcflags;
1812 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001813 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001814 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815
Yury Selivanov75445082015-05-11 22:57:16 -04001816 if (is_async) {
1817 assert(s->kind == AsyncFunctionDef_kind);
1818
1819 args = s->v.AsyncFunctionDef.args;
1820 returns = s->v.AsyncFunctionDef.returns;
1821 decos = s->v.AsyncFunctionDef.decorator_list;
1822 name = s->v.AsyncFunctionDef.name;
1823 body = s->v.AsyncFunctionDef.body;
1824
1825 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1826 } else {
1827 assert(s->kind == FunctionDef_kind);
1828
1829 args = s->v.FunctionDef.args;
1830 returns = s->v.FunctionDef.returns;
1831 decos = s->v.FunctionDef.decorator_list;
1832 name = s->v.FunctionDef.name;
1833 body = s->v.FunctionDef.body;
1834
1835 scope_type = COMPILER_SCOPE_FUNCTION;
1836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (!compiler_decorators(c, decos))
1839 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001840
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001841 funcflags = compiler_default_arguments(c, args);
1842 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001844 }
1845
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001846 annotations = compiler_visit_annotations(c, args, returns);
1847 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 return 0;
1849 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001850 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001851 funcflags |= 0x04;
1852 }
1853
1854 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1855 return 0;
1856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Yury Selivanov75445082015-05-11 22:57:16 -04001858 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001860 if (docstring && c->c_optimize < 2) {
1861 if (st->v.Expr.value->kind == Constant_kind)
1862 first_const = st->v.Expr.value->v.Constant.value;
1863 else
1864 first_const = st->v.Expr.value->v.Str.s;
1865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1867 compiler_exit_scope(c);
1868 return 0;
1869 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 c->u->u_argcount = asdl_seq_LEN(args->args);
1872 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001873 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 /* if there was a docstring, we need to skip the first statement */
1875 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001876 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 VISIT_IN_SCOPE(c, stmt, st);
1878 }
1879 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001880 qualname = c->u->u_qualname;
1881 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001883 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001884 Py_XDECREF(qualname);
1885 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001887 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001889 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001890 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* decorators */
1894 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1895 ADDOP_I(c, CALL_FUNCTION, 1);
1896 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897
Yury Selivanov75445082015-05-11 22:57:16 -04001898 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899}
1900
1901static int
1902compiler_class(struct compiler *c, stmt_ty s)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PyCodeObject *co;
1905 PyObject *str;
1906 int i;
1907 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (!compiler_decorators(c, decos))
1910 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* ultimately generate code for:
1913 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1914 where:
1915 <func> is a function/closure created from the class body;
1916 it has a single argument (__locals__) where the dict
1917 (or MutableSequence) representing the locals is passed
1918 <name> is the class name
1919 <bases> is the positional arguments and *varargs argument
1920 <keywords> is the keyword arguments and **kwds argument
1921 This borrows from compiler_call.
1922 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1926 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 return 0;
1928 /* this block represents what we do in the new scope */
1929 {
1930 /* use the class name for name mangling */
1931 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001932 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 /* load (global) __name__ ... */
1934 str = PyUnicode_InternFromString("__name__");
1935 if (!str || !compiler_nameop(c, str, Load)) {
1936 Py_XDECREF(str);
1937 compiler_exit_scope(c);
1938 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 Py_DECREF(str);
1941 /* ... and store it as __module__ */
1942 str = PyUnicode_InternFromString("__module__");
1943 if (!str || !compiler_nameop(c, str, Store)) {
1944 Py_XDECREF(str);
1945 compiler_exit_scope(c);
1946 return 0;
1947 }
1948 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001949 assert(c->u->u_qualname);
1950 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001951 str = PyUnicode_InternFromString("__qualname__");
1952 if (!str || !compiler_nameop(c, str, Store)) {
1953 Py_XDECREF(str);
1954 compiler_exit_scope(c);
1955 return 0;
1956 }
1957 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /* compile the body proper */
1959 if (!compiler_body(c, s->v.ClassDef.body)) {
1960 compiler_exit_scope(c);
1961 return 0;
1962 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001963 if (c->u->u_ste->ste_needs_class_closure) {
1964 /* return the (empty) __class__ cell */
1965 str = PyUnicode_InternFromString("__class__");
1966 if (str == NULL) {
1967 compiler_exit_scope(c);
1968 return 0;
1969 }
1970 i = compiler_lookup_arg(c->u->u_cellvars, str);
1971 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001972 if (i < 0) {
1973 compiler_exit_scope(c);
1974 return 0;
1975 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001976 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* Return the cell where to store __class__ */
1978 ADDOP_I(c, LOAD_CLOSURE, i);
1979 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001980 else {
1981 assert(PyDict_Size(c->u->u_cellvars) == 0);
1982 /* This happens when nobody references the cell. Return None. */
1983 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1984 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1986 /* create the code object */
1987 co = assemble(c, 1);
1988 }
1989 /* leave the new scope */
1990 compiler_exit_scope(c);
1991 if (co == NULL)
1992 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* 2. load the 'build_class' function */
1995 ADDOP(c, LOAD_BUILD_CLASS);
1996
1997 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001998 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Py_DECREF(co);
2000
2001 /* 4. load class name */
2002 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2003
2004 /* 5. generate the rest of the code for the call */
2005 if (!compiler_call_helper(c, 2,
2006 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002007 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return 0;
2009
2010 /* 6. apply decorators */
2011 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2012 ADDOP_I(c, CALL_FUNCTION, 1);
2013 }
2014
2015 /* 7. store into <name> */
2016 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2017 return 0;
2018 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019}
2020
2021static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002022compiler_ifexp(struct compiler *c, expr_ty e)
2023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 basicblock *end, *next;
2025
2026 assert(e->kind == IfExp_kind);
2027 end = compiler_new_block(c);
2028 if (end == NULL)
2029 return 0;
2030 next = compiler_new_block(c);
2031 if (next == NULL)
2032 return 0;
2033 VISIT(c, expr, e->v.IfExp.test);
2034 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2035 VISIT(c, expr, e->v.IfExp.body);
2036 ADDOP_JREL(c, JUMP_FORWARD, end);
2037 compiler_use_next_block(c, next);
2038 VISIT(c, expr, e->v.IfExp.orelse);
2039 compiler_use_next_block(c, end);
2040 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002041}
2042
2043static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044compiler_lambda(struct compiler *c, expr_ty e)
2045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002047 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 arguments_ty args = e->v.Lambda.args;
2051 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (!name) {
2054 name = PyUnicode_InternFromString("<lambda>");
2055 if (!name)
2056 return 0;
2057 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002059 funcflags = compiler_default_arguments(c, args);
2060 if (funcflags == -1) {
2061 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002063
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002064 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002065 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* Make None the first constant, so the lambda can't have a
2069 docstring. */
2070 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2071 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 c->u->u_argcount = asdl_seq_LEN(args->args);
2074 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2075 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2076 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002077 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 }
2079 else {
2080 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002081 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002083 qualname = c->u->u_qualname;
2084 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002086 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002089 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002090 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 Py_DECREF(co);
2092
2093 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094}
2095
2096static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097compiler_if(struct compiler *c, stmt_ty s)
2098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 basicblock *end, *next;
2100 int constant;
2101 assert(s->kind == If_kind);
2102 end = compiler_new_block(c);
2103 if (end == NULL)
2104 return 0;
2105
Georg Brandl8334fd92010-12-04 10:26:46 +00002106 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* constant = 0: "if 0"
2108 * constant = 1: "if 1", "if 2", ...
2109 * constant = -1: rest */
2110 if (constant == 0) {
2111 if (s->v.If.orelse)
2112 VISIT_SEQ(c, stmt, s->v.If.orelse);
2113 } else if (constant == 1) {
2114 VISIT_SEQ(c, stmt, s->v.If.body);
2115 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002116 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 next = compiler_new_block(c);
2118 if (next == NULL)
2119 return 0;
2120 }
2121 else
2122 next = end;
2123 VISIT(c, expr, s->v.If.test);
2124 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2125 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002126 if (asdl_seq_LEN(s->v.If.orelse)) {
2127 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 compiler_use_next_block(c, next);
2129 VISIT_SEQ(c, stmt, s->v.If.orelse);
2130 }
2131 }
2132 compiler_use_next_block(c, end);
2133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134}
2135
2136static int
2137compiler_for(struct compiler *c, stmt_ty s)
2138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 start = compiler_new_block(c);
2142 cleanup = compiler_new_block(c);
2143 end = compiler_new_block(c);
2144 if (start == NULL || end == NULL || cleanup == NULL)
2145 return 0;
2146 ADDOP_JREL(c, SETUP_LOOP, end);
2147 if (!compiler_push_fblock(c, LOOP, start))
2148 return 0;
2149 VISIT(c, expr, s->v.For.iter);
2150 ADDOP(c, GET_ITER);
2151 compiler_use_next_block(c, start);
2152 ADDOP_JREL(c, FOR_ITER, cleanup);
2153 VISIT(c, expr, s->v.For.target);
2154 VISIT_SEQ(c, stmt, s->v.For.body);
2155 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2156 compiler_use_next_block(c, cleanup);
2157 ADDOP(c, POP_BLOCK);
2158 compiler_pop_fblock(c, LOOP, start);
2159 VISIT_SEQ(c, stmt, s->v.For.orelse);
2160 compiler_use_next_block(c, end);
2161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162}
2163
Yury Selivanov75445082015-05-11 22:57:16 -04002164
2165static int
2166compiler_async_for(struct compiler *c, stmt_ty s)
2167{
2168 static PyObject *stopiter_error = NULL;
2169 basicblock *try, *except, *end, *after_try, *try_cleanup,
2170 *after_loop, *after_loop_else;
2171
2172 if (stopiter_error == NULL) {
2173 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2174 if (stopiter_error == NULL)
2175 return 0;
2176 }
2177
2178 try = compiler_new_block(c);
2179 except = compiler_new_block(c);
2180 end = compiler_new_block(c);
2181 after_try = compiler_new_block(c);
2182 try_cleanup = compiler_new_block(c);
2183 after_loop = compiler_new_block(c);
2184 after_loop_else = compiler_new_block(c);
2185
2186 if (try == NULL || except == NULL || end == NULL
2187 || after_try == NULL || try_cleanup == NULL)
2188 return 0;
2189
2190 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2191 if (!compiler_push_fblock(c, LOOP, try))
2192 return 0;
2193
2194 VISIT(c, expr, s->v.AsyncFor.iter);
2195 ADDOP(c, GET_AITER);
2196 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2197 ADDOP(c, YIELD_FROM);
2198
2199 compiler_use_next_block(c, try);
2200
2201
2202 ADDOP_JREL(c, SETUP_EXCEPT, except);
2203 if (!compiler_push_fblock(c, EXCEPT, try))
2204 return 0;
2205
2206 ADDOP(c, GET_ANEXT);
2207 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2208 ADDOP(c, YIELD_FROM);
2209 VISIT(c, expr, s->v.AsyncFor.target);
2210 ADDOP(c, POP_BLOCK);
2211 compiler_pop_fblock(c, EXCEPT, try);
2212 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2213
2214
2215 compiler_use_next_block(c, except);
2216 ADDOP(c, DUP_TOP);
2217 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2218 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2219 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2220
2221 ADDOP(c, POP_TOP);
2222 ADDOP(c, POP_TOP);
2223 ADDOP(c, POP_TOP);
2224 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2225 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2226 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2227
2228
2229 compiler_use_next_block(c, try_cleanup);
2230 ADDOP(c, END_FINALLY);
2231
2232 compiler_use_next_block(c, after_try);
2233 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2234 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2235
2236 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2237 compiler_pop_fblock(c, LOOP, try);
2238
2239 compiler_use_next_block(c, after_loop);
2240 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2241
2242 compiler_use_next_block(c, after_loop_else);
2243 VISIT_SEQ(c, stmt, s->v.For.orelse);
2244
2245 compiler_use_next_block(c, end);
2246
2247 return 1;
2248}
2249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250static int
2251compiler_while(struct compiler *c, stmt_ty s)
2252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002254 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 if (constant == 0) {
2257 if (s->v.While.orelse)
2258 VISIT_SEQ(c, stmt, s->v.While.orelse);
2259 return 1;
2260 }
2261 loop = compiler_new_block(c);
2262 end = compiler_new_block(c);
2263 if (constant == -1) {
2264 anchor = compiler_new_block(c);
2265 if (anchor == NULL)
2266 return 0;
2267 }
2268 if (loop == NULL || end == NULL)
2269 return 0;
2270 if (s->v.While.orelse) {
2271 orelse = compiler_new_block(c);
2272 if (orelse == NULL)
2273 return 0;
2274 }
2275 else
2276 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 ADDOP_JREL(c, SETUP_LOOP, end);
2279 compiler_use_next_block(c, loop);
2280 if (!compiler_push_fblock(c, LOOP, loop))
2281 return 0;
2282 if (constant == -1) {
2283 VISIT(c, expr, s->v.While.test);
2284 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2285 }
2286 VISIT_SEQ(c, stmt, s->v.While.body);
2287 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* XXX should the two POP instructions be in a separate block
2290 if there is no else clause ?
2291 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002293 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002295 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 compiler_pop_fblock(c, LOOP, loop);
2297 if (orelse != NULL) /* what if orelse is just pass? */
2298 VISIT_SEQ(c, stmt, s->v.While.orelse);
2299 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302}
2303
2304static int
2305compiler_continue(struct compiler *c)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2308 static const char IN_FINALLY_ERROR_MSG[] =
2309 "'continue' not supported inside 'finally' clause";
2310 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 if (!c->u->u_nfblocks)
2313 return compiler_error(c, LOOP_ERROR_MSG);
2314 i = c->u->u_nfblocks - 1;
2315 switch (c->u->u_fblock[i].fb_type) {
2316 case LOOP:
2317 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2318 break;
2319 case EXCEPT:
2320 case FINALLY_TRY:
2321 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2322 /* Prevent continue anywhere under a finally
2323 even if hidden in a sub-try or except. */
2324 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2325 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2326 }
2327 if (i == -1)
2328 return compiler_error(c, LOOP_ERROR_MSG);
2329 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2330 break;
2331 case FINALLY_END:
2332 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336}
2337
2338/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339
2340 SETUP_FINALLY L
2341 <code for body>
2342 POP_BLOCK
2343 LOAD_CONST <None>
2344 L: <code for finalbody>
2345 END_FINALLY
2346
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347 The special instructions use the block stack. Each block
2348 stack entry contains the instruction that created it (here
2349 SETUP_FINALLY), the level of the value stack at the time the
2350 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Pushes the current value stack level and the label
2354 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 Pops en entry from the block stack, and pops the value
2357 stack until its level is the same as indicated on the
2358 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Pops a variable number of entries from the *value* stack
2361 and re-raises the exception they specify. The number of
2362 entries popped depends on the (pseudo) exception type.
2363
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364 The block stack is unwound when an exception is raised:
2365 when a SETUP_FINALLY entry is found, the exception is pushed
2366 onto the value stack (and the exception condition is cleared),
2367 and the interpreter jumps to the label gotten from the block
2368 stack.
2369*/
2370
2371static int
2372compiler_try_finally(struct compiler *c, stmt_ty s)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 basicblock *body, *end;
2375 body = compiler_new_block(c);
2376 end = compiler_new_block(c);
2377 if (body == NULL || end == NULL)
2378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 ADDOP_JREL(c, SETUP_FINALLY, end);
2381 compiler_use_next_block(c, body);
2382 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2383 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002384 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2385 if (!compiler_try_except(c, s))
2386 return 0;
2387 }
2388 else {
2389 VISIT_SEQ(c, stmt, s->v.Try.body);
2390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 ADDOP(c, POP_BLOCK);
2392 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2395 compiler_use_next_block(c, end);
2396 if (!compiler_push_fblock(c, FINALLY_END, end))
2397 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002398 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 ADDOP(c, END_FINALLY);
2400 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403}
2404
2405/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002406 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 (The contents of the value stack is shown in [], with the top
2408 at the right; 'tb' is trace-back info, 'val' the exception's
2409 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410
2411 Value stack Label Instruction Argument
2412 [] SETUP_EXCEPT L1
2413 [] <code for S>
2414 [] POP_BLOCK
2415 [] JUMP_FORWARD L0
2416
2417 [tb, val, exc] L1: DUP )
2418 [tb, val, exc, exc] <evaluate E1> )
2419 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2420 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2421 [tb, val, exc] POP
2422 [tb, val] <assign to V1> (or POP if no V1)
2423 [tb] POP
2424 [] <code for S1>
2425 JUMP_FORWARD L0
2426
2427 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 .............................etc.......................
2429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2431
2432 [] L0: <next statement>
2433
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434 Of course, parts are not generated if Vi or Ei is not present.
2435*/
2436static int
2437compiler_try_except(struct compiler *c, stmt_ty s)
2438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002440 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 body = compiler_new_block(c);
2443 except = compiler_new_block(c);
2444 orelse = compiler_new_block(c);
2445 end = compiler_new_block(c);
2446 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2447 return 0;
2448 ADDOP_JREL(c, SETUP_EXCEPT, except);
2449 compiler_use_next_block(c, body);
2450 if (!compiler_push_fblock(c, EXCEPT, body))
2451 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002452 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 ADDOP(c, POP_BLOCK);
2454 compiler_pop_fblock(c, EXCEPT, body);
2455 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002456 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 compiler_use_next_block(c, except);
2458 for (i = 0; i < n; i++) {
2459 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002460 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (!handler->v.ExceptHandler.type && i < n-1)
2462 return compiler_error(c, "default 'except:' must be last");
2463 c->u->u_lineno_set = 0;
2464 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002465 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 except = compiler_new_block(c);
2467 if (except == NULL)
2468 return 0;
2469 if (handler->v.ExceptHandler.type) {
2470 ADDOP(c, DUP_TOP);
2471 VISIT(c, expr, handler->v.ExceptHandler.type);
2472 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2473 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2474 }
2475 ADDOP(c, POP_TOP);
2476 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002477 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002478
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002479 cleanup_end = compiler_new_block(c);
2480 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002481 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002482 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002483
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002484 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2485 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002487 /*
2488 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002489 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002490 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002491 try:
2492 # body
2493 finally:
2494 name = None
2495 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002496 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002498 /* second try: */
2499 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2500 compiler_use_next_block(c, cleanup_body);
2501 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2502 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002504 /* second # body */
2505 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2506 ADDOP(c, POP_BLOCK);
2507 ADDOP(c, POP_EXCEPT);
2508 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002510 /* finally: */
2511 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2512 compiler_use_next_block(c, cleanup_end);
2513 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2514 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002516 /* name = None */
2517 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2518 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002520 /* del name */
2521 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002523 ADDOP(c, END_FINALLY);
2524 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 }
2526 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002527 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002529 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002530 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002531 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532
Guido van Rossumb940e112007-01-10 16:19:56 +00002533 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002534 ADDOP(c, POP_TOP);
2535 compiler_use_next_block(c, cleanup_body);
2536 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2537 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002539 ADDOP(c, POP_EXCEPT);
2540 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 }
2542 ADDOP_JREL(c, JUMP_FORWARD, end);
2543 compiler_use_next_block(c, except);
2544 }
2545 ADDOP(c, END_FINALLY);
2546 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002547 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 compiler_use_next_block(c, end);
2549 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550}
2551
2552static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002553compiler_try(struct compiler *c, stmt_ty s) {
2554 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2555 return compiler_try_finally(c, s);
2556 else
2557 return compiler_try_except(c, s);
2558}
2559
2560
2561static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562compiler_import_as(struct compiler *c, identifier name, identifier asname)
2563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* The IMPORT_NAME opcode was already generated. This function
2565 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 If there is a dot in name, we need to split it and emit a
2568 LOAD_ATTR for each name.
2569 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2571 PyUnicode_GET_LENGTH(name), 1);
2572 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002573 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002576 Py_ssize_t pos = dot + 1;
2577 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002579 dot = PyUnicode_FindChar(name, '.', pos,
2580 PyUnicode_GET_LENGTH(name), 1);
2581 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002582 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 attr = PyUnicode_Substring(name, pos,
2584 (dot != -1) ? dot :
2585 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002587 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 ADDOP_O(c, LOAD_ATTR, attr, names);
2589 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 }
2592 }
2593 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594}
2595
2596static int
2597compiler_import(struct compiler *c, stmt_ty s)
2598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* The Import node stores a module name like a.b.c as a single
2600 string. This is convenient for all cases except
2601 import a.b.c as d
2602 where we need to parse that string to extract the individual
2603 module names.
2604 XXX Perhaps change the representation to make this case simpler?
2605 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002606 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 for (i = 0; i < n; i++) {
2609 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2610 int r;
2611 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 level = PyLong_FromLong(0);
2614 if (level == NULL)
2615 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 ADDOP_O(c, LOAD_CONST, level, consts);
2618 Py_DECREF(level);
2619 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2620 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 if (alias->asname) {
2623 r = compiler_import_as(c, alias->name, alias->asname);
2624 if (!r)
2625 return r;
2626 }
2627 else {
2628 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 Py_ssize_t dot = PyUnicode_FindChar(
2630 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002631 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002633 if (tmp == NULL)
2634 return 0;
2635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 Py_DECREF(tmp);
2639 }
2640 if (!r)
2641 return r;
2642 }
2643 }
2644 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645}
2646
2647static int
2648compiler_from_import(struct compiler *c, stmt_ty s)
2649{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002650 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 PyObject *names = PyTuple_New(n);
2653 PyObject *level;
2654 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (!empty_string) {
2657 empty_string = PyUnicode_FromString("");
2658 if (!empty_string)
2659 return 0;
2660 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (!names)
2663 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 level = PyLong_FromLong(s->v.ImportFrom.level);
2666 if (!level) {
2667 Py_DECREF(names);
2668 return 0;
2669 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 /* build up the names */
2672 for (i = 0; i < n; i++) {
2673 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2674 Py_INCREF(alias->name);
2675 PyTuple_SET_ITEM(names, i, alias->name);
2676 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2679 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2680 Py_DECREF(level);
2681 Py_DECREF(names);
2682 return compiler_error(c, "from __future__ imports must occur "
2683 "at the beginning of the file");
2684 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 ADDOP_O(c, LOAD_CONST, level, consts);
2687 Py_DECREF(level);
2688 ADDOP_O(c, LOAD_CONST, names, consts);
2689 Py_DECREF(names);
2690 if (s->v.ImportFrom.module) {
2691 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2692 }
2693 else {
2694 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2695 }
2696 for (i = 0; i < n; i++) {
2697 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2698 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 assert(n == 1);
2702 ADDOP(c, IMPORT_STAR);
2703 return 1;
2704 }
2705
2706 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2707 store_name = alias->name;
2708 if (alias->asname)
2709 store_name = alias->asname;
2710
2711 if (!compiler_nameop(c, store_name, Store)) {
2712 Py_DECREF(names);
2713 return 0;
2714 }
2715 }
2716 /* remove imported module */
2717 ADDOP(c, POP_TOP);
2718 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719}
2720
2721static int
2722compiler_assert(struct compiler *c, stmt_ty s)
2723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 static PyObject *assertion_error = NULL;
2725 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002726 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
Georg Brandl8334fd92010-12-04 10:26:46 +00002728 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 return 1;
2730 if (assertion_error == NULL) {
2731 assertion_error = PyUnicode_InternFromString("AssertionError");
2732 if (assertion_error == NULL)
2733 return 0;
2734 }
2735 if (s->v.Assert.test->kind == Tuple_kind &&
2736 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002737 msg = PyUnicode_FromString("assertion is always true, "
2738 "perhaps remove parentheses?");
2739 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002741 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2742 c->c_filename, c->u->u_lineno,
2743 NULL, NULL) == -1) {
2744 Py_DECREF(msg);
2745 return 0;
2746 }
2747 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 }
2749 VISIT(c, expr, s->v.Assert.test);
2750 end = compiler_new_block(c);
2751 if (end == NULL)
2752 return 0;
2753 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2754 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2755 if (s->v.Assert.msg) {
2756 VISIT(c, expr, s->v.Assert.msg);
2757 ADDOP_I(c, CALL_FUNCTION, 1);
2758 }
2759 ADDOP_I(c, RAISE_VARARGS, 1);
2760 compiler_use_next_block(c, end);
2761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762}
2763
2764static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002765compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2766{
2767 if (c->c_interactive && c->c_nestlevel <= 1) {
2768 VISIT(c, expr, value);
2769 ADDOP(c, PRINT_EXPR);
2770 return 1;
2771 }
2772
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002773 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002774 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002775 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002776 }
2777
2778 VISIT(c, expr, value);
2779 ADDOP(c, POP_TOP);
2780 return 1;
2781}
2782
2783static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784compiler_visit_stmt(struct compiler *c, stmt_ty s)
2785{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002786 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 /* Always assign a lineno to the next instruction for a stmt. */
2789 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002790 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 switch (s->kind) {
2794 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002795 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 case ClassDef_kind:
2797 return compiler_class(c, s);
2798 case Return_kind:
2799 if (c->u->u_ste->ste_type != FunctionBlock)
2800 return compiler_error(c, "'return' outside function");
2801 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002802 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2803 return compiler_error(
2804 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 VISIT(c, expr, s->v.Return.value);
2806 }
2807 else
2808 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2809 ADDOP(c, RETURN_VALUE);
2810 break;
2811 case Delete_kind:
2812 VISIT_SEQ(c, expr, s->v.Delete.targets)
2813 break;
2814 case Assign_kind:
2815 n = asdl_seq_LEN(s->v.Assign.targets);
2816 VISIT(c, expr, s->v.Assign.value);
2817 for (i = 0; i < n; i++) {
2818 if (i < n - 1)
2819 ADDOP(c, DUP_TOP);
2820 VISIT(c, expr,
2821 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2822 }
2823 break;
2824 case AugAssign_kind:
2825 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002826 case AnnAssign_kind:
2827 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 case For_kind:
2829 return compiler_for(c, s);
2830 case While_kind:
2831 return compiler_while(c, s);
2832 case If_kind:
2833 return compiler_if(c, s);
2834 case Raise_kind:
2835 n = 0;
2836 if (s->v.Raise.exc) {
2837 VISIT(c, expr, s->v.Raise.exc);
2838 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002839 if (s->v.Raise.cause) {
2840 VISIT(c, expr, s->v.Raise.cause);
2841 n++;
2842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002844 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002846 case Try_kind:
2847 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 case Assert_kind:
2849 return compiler_assert(c, s);
2850 case Import_kind:
2851 return compiler_import(c, s);
2852 case ImportFrom_kind:
2853 return compiler_from_import(c, s);
2854 case Global_kind:
2855 case Nonlocal_kind:
2856 break;
2857 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002858 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 case Pass_kind:
2860 break;
2861 case Break_kind:
2862 if (!compiler_in_loop(c))
2863 return compiler_error(c, "'break' outside loop");
2864 ADDOP(c, BREAK_LOOP);
2865 break;
2866 case Continue_kind:
2867 return compiler_continue(c);
2868 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002869 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002870 case AsyncFunctionDef_kind:
2871 return compiler_function(c, s, 1);
2872 case AsyncWith_kind:
2873 return compiler_async_with(c, s, 0);
2874 case AsyncFor_kind:
2875 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 }
Yury Selivanov75445082015-05-11 22:57:16 -04002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879}
2880
2881static int
2882unaryop(unaryop_ty op)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 switch (op) {
2885 case Invert:
2886 return UNARY_INVERT;
2887 case Not:
2888 return UNARY_NOT;
2889 case UAdd:
2890 return UNARY_POSITIVE;
2891 case USub:
2892 return UNARY_NEGATIVE;
2893 default:
2894 PyErr_Format(PyExc_SystemError,
2895 "unary op %d should not be possible", op);
2896 return 0;
2897 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898}
2899
2900static int
2901binop(struct compiler *c, operator_ty op)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 switch (op) {
2904 case Add:
2905 return BINARY_ADD;
2906 case Sub:
2907 return BINARY_SUBTRACT;
2908 case Mult:
2909 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002910 case MatMult:
2911 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 case Div:
2913 return BINARY_TRUE_DIVIDE;
2914 case Mod:
2915 return BINARY_MODULO;
2916 case Pow:
2917 return BINARY_POWER;
2918 case LShift:
2919 return BINARY_LSHIFT;
2920 case RShift:
2921 return BINARY_RSHIFT;
2922 case BitOr:
2923 return BINARY_OR;
2924 case BitXor:
2925 return BINARY_XOR;
2926 case BitAnd:
2927 return BINARY_AND;
2928 case FloorDiv:
2929 return BINARY_FLOOR_DIVIDE;
2930 default:
2931 PyErr_Format(PyExc_SystemError,
2932 "binary op %d should not be possible", op);
2933 return 0;
2934 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935}
2936
2937static int
2938cmpop(cmpop_ty op)
2939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 switch (op) {
2941 case Eq:
2942 return PyCmp_EQ;
2943 case NotEq:
2944 return PyCmp_NE;
2945 case Lt:
2946 return PyCmp_LT;
2947 case LtE:
2948 return PyCmp_LE;
2949 case Gt:
2950 return PyCmp_GT;
2951 case GtE:
2952 return PyCmp_GE;
2953 case Is:
2954 return PyCmp_IS;
2955 case IsNot:
2956 return PyCmp_IS_NOT;
2957 case In:
2958 return PyCmp_IN;
2959 case NotIn:
2960 return PyCmp_NOT_IN;
2961 default:
2962 return PyCmp_BAD;
2963 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964}
2965
2966static int
2967inplace_binop(struct compiler *c, operator_ty op)
2968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 switch (op) {
2970 case Add:
2971 return INPLACE_ADD;
2972 case Sub:
2973 return INPLACE_SUBTRACT;
2974 case Mult:
2975 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002976 case MatMult:
2977 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 case Div:
2979 return INPLACE_TRUE_DIVIDE;
2980 case Mod:
2981 return INPLACE_MODULO;
2982 case Pow:
2983 return INPLACE_POWER;
2984 case LShift:
2985 return INPLACE_LSHIFT;
2986 case RShift:
2987 return INPLACE_RSHIFT;
2988 case BitOr:
2989 return INPLACE_OR;
2990 case BitXor:
2991 return INPLACE_XOR;
2992 case BitAnd:
2993 return INPLACE_AND;
2994 case FloorDiv:
2995 return INPLACE_FLOOR_DIVIDE;
2996 default:
2997 PyErr_Format(PyExc_SystemError,
2998 "inplace binary op %d should not be possible", op);
2999 return 0;
3000 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001}
3002
3003static int
3004compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3005{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003006 int op, scope;
3007 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 PyObject *dict = c->u->u_names;
3011 PyObject *mangled;
3012 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 mangled = _Py_Mangle(c->u->u_private, name);
3015 if (!mangled)
3016 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003017
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003018 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
3019 PyUnicode_CompareWithASCIIString(name, "True") &&
3020 PyUnicode_CompareWithASCIIString(name, "False"));
3021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 op = 0;
3023 optype = OP_NAME;
3024 scope = PyST_GetScope(c->u->u_ste, mangled);
3025 switch (scope) {
3026 case FREE:
3027 dict = c->u->u_freevars;
3028 optype = OP_DEREF;
3029 break;
3030 case CELL:
3031 dict = c->u->u_cellvars;
3032 optype = OP_DEREF;
3033 break;
3034 case LOCAL:
3035 if (c->u->u_ste->ste_type == FunctionBlock)
3036 optype = OP_FAST;
3037 break;
3038 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003039 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 optype = OP_GLOBAL;
3041 break;
3042 case GLOBAL_EXPLICIT:
3043 optype = OP_GLOBAL;
3044 break;
3045 default:
3046 /* scope can be 0 */
3047 break;
3048 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003051 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 switch (optype) {
3054 case OP_DEREF:
3055 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003056 case Load:
3057 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3058 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 case Store: op = STORE_DEREF; break;
3060 case AugLoad:
3061 case AugStore:
3062 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003063 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 case Param:
3065 default:
3066 PyErr_SetString(PyExc_SystemError,
3067 "param invalid for deref variable");
3068 return 0;
3069 }
3070 break;
3071 case OP_FAST:
3072 switch (ctx) {
3073 case Load: op = LOAD_FAST; break;
3074 case Store: op = STORE_FAST; break;
3075 case Del: op = DELETE_FAST; break;
3076 case AugLoad:
3077 case AugStore:
3078 break;
3079 case Param:
3080 default:
3081 PyErr_SetString(PyExc_SystemError,
3082 "param invalid for local variable");
3083 return 0;
3084 }
3085 ADDOP_O(c, op, mangled, varnames);
3086 Py_DECREF(mangled);
3087 return 1;
3088 case OP_GLOBAL:
3089 switch (ctx) {
3090 case Load: op = LOAD_GLOBAL; break;
3091 case Store: op = STORE_GLOBAL; break;
3092 case Del: op = DELETE_GLOBAL; break;
3093 case AugLoad:
3094 case AugStore:
3095 break;
3096 case Param:
3097 default:
3098 PyErr_SetString(PyExc_SystemError,
3099 "param invalid for global variable");
3100 return 0;
3101 }
3102 break;
3103 case OP_NAME:
3104 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003105 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 case Store: op = STORE_NAME; break;
3107 case Del: op = DELETE_NAME; break;
3108 case AugLoad:
3109 case AugStore:
3110 break;
3111 case Param:
3112 default:
3113 PyErr_SetString(PyExc_SystemError,
3114 "param invalid for name variable");
3115 return 0;
3116 }
3117 break;
3118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 assert(op);
3121 arg = compiler_add_o(c, dict, mangled);
3122 Py_DECREF(mangled);
3123 if (arg < 0)
3124 return 0;
3125 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126}
3127
3128static int
3129compiler_boolop(struct compiler *c, expr_ty e)
3130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003132 int jumpi;
3133 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 assert(e->kind == BoolOp_kind);
3137 if (e->v.BoolOp.op == And)
3138 jumpi = JUMP_IF_FALSE_OR_POP;
3139 else
3140 jumpi = JUMP_IF_TRUE_OR_POP;
3141 end = compiler_new_block(c);
3142 if (end == NULL)
3143 return 0;
3144 s = e->v.BoolOp.values;
3145 n = asdl_seq_LEN(s) - 1;
3146 assert(n >= 0);
3147 for (i = 0; i < n; ++i) {
3148 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3149 ADDOP_JABS(c, jumpi, end);
3150 }
3151 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3152 compiler_use_next_block(c, end);
3153 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154}
3155
3156static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003157starunpack_helper(struct compiler *c, asdl_seq *elts,
3158 int single_op, int inner_op, int outer_op)
3159{
3160 Py_ssize_t n = asdl_seq_LEN(elts);
3161 Py_ssize_t i, nsubitems = 0, nseen = 0;
3162 for (i = 0; i < n; i++) {
3163 expr_ty elt = asdl_seq_GET(elts, i);
3164 if (elt->kind == Starred_kind) {
3165 if (nseen) {
3166 ADDOP_I(c, inner_op, nseen);
3167 nseen = 0;
3168 nsubitems++;
3169 }
3170 VISIT(c, expr, elt->v.Starred.value);
3171 nsubitems++;
3172 }
3173 else {
3174 VISIT(c, expr, elt);
3175 nseen++;
3176 }
3177 }
3178 if (nsubitems) {
3179 if (nseen) {
3180 ADDOP_I(c, inner_op, nseen);
3181 nsubitems++;
3182 }
3183 ADDOP_I(c, outer_op, nsubitems);
3184 }
3185 else
3186 ADDOP_I(c, single_op, nseen);
3187 return 1;
3188}
3189
3190static int
3191assignment_helper(struct compiler *c, asdl_seq *elts)
3192{
3193 Py_ssize_t n = asdl_seq_LEN(elts);
3194 Py_ssize_t i;
3195 int seen_star = 0;
3196 for (i = 0; i < n; i++) {
3197 expr_ty elt = asdl_seq_GET(elts, i);
3198 if (elt->kind == Starred_kind && !seen_star) {
3199 if ((i >= (1 << 8)) ||
3200 (n-i-1 >= (INT_MAX >> 8)))
3201 return compiler_error(c,
3202 "too many expressions in "
3203 "star-unpacking assignment");
3204 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3205 seen_star = 1;
3206 asdl_seq_SET(elts, i, elt->v.Starred.value);
3207 }
3208 else if (elt->kind == Starred_kind) {
3209 return compiler_error(c,
3210 "two starred expressions in assignment");
3211 }
3212 }
3213 if (!seen_star) {
3214 ADDOP_I(c, UNPACK_SEQUENCE, n);
3215 }
3216 VISIT_SEQ(c, expr, elts);
3217 return 1;
3218}
3219
3220static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221compiler_list(struct compiler *c, expr_ty e)
3222{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003223 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003225 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003227 else if (e->v.List.ctx == Load) {
3228 return starunpack_helper(c, elts,
3229 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003231 else
3232 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234}
3235
3236static int
3237compiler_tuple(struct compiler *c, expr_ty e)
3238{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003239 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003241 return assignment_helper(c, elts);
3242 }
3243 else if (e->v.Tuple.ctx == Load) {
3244 return starunpack_helper(c, elts,
3245 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3246 }
3247 else
3248 VISIT_SEQ(c, expr, elts);
3249 return 1;
3250}
3251
3252static int
3253compiler_set(struct compiler *c, expr_ty e)
3254{
3255 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3256 BUILD_SET, BUILD_SET_UNPACK);
3257}
3258
3259static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003260are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3261{
3262 Py_ssize_t i;
3263 for (i = begin; i < end; i++) {
3264 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3265 if (key == NULL || !is_const(key))
3266 return 0;
3267 }
3268 return 1;
3269}
3270
3271static int
3272compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3273{
3274 Py_ssize_t i, n = end - begin;
3275 PyObject *keys, *key;
3276 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3277 for (i = begin; i < end; i++) {
3278 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3279 }
3280 keys = PyTuple_New(n);
3281 if (keys == NULL) {
3282 return 0;
3283 }
3284 for (i = begin; i < end; i++) {
3285 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3286 Py_INCREF(key);
3287 PyTuple_SET_ITEM(keys, i - begin, key);
3288 }
3289 ADDOP_N(c, LOAD_CONST, keys, consts);
3290 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3291 }
3292 else {
3293 for (i = begin; i < end; i++) {
3294 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3295 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3296 }
3297 ADDOP_I(c, BUILD_MAP, n);
3298 }
3299 return 1;
3300}
3301
3302static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003303compiler_dict(struct compiler *c, expr_ty e)
3304{
Victor Stinner976bb402016-03-23 11:36:19 +01003305 Py_ssize_t i, n, elements;
3306 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003307 int is_unpacking = 0;
3308 n = asdl_seq_LEN(e->v.Dict.values);
3309 containers = 0;
3310 elements = 0;
3311 for (i = 0; i < n; i++) {
3312 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3313 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003314 if (!compiler_subdict(c, e, i - elements, i))
3315 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003316 containers++;
3317 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003319 if (is_unpacking) {
3320 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3321 containers++;
3322 }
3323 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003324 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 }
3326 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003327 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003328 if (!compiler_subdict(c, e, n - elements, n))
3329 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003330 containers++;
3331 }
3332 /* If there is more than one dict, they need to be merged into a new
3333 * dict. If there is one dict and it's an unpacking, then it needs
3334 * to be copied into a new dict." */
3335 while (containers > 1 || is_unpacking) {
3336 int oparg = containers < 255 ? containers : 255;
3337 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3338 containers -= (oparg - 1);
3339 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 }
3341 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342}
3343
3344static int
3345compiler_compare(struct compiler *c, expr_ty e)
3346{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003347 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3351 VISIT(c, expr, e->v.Compare.left);
3352 n = asdl_seq_LEN(e->v.Compare.ops);
3353 assert(n > 0);
3354 if (n > 1) {
3355 cleanup = compiler_new_block(c);
3356 if (cleanup == NULL)
3357 return 0;
3358 VISIT(c, expr,
3359 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3360 }
3361 for (i = 1; i < n; i++) {
3362 ADDOP(c, DUP_TOP);
3363 ADDOP(c, ROT_THREE);
3364 ADDOP_I(c, COMPARE_OP,
3365 cmpop((cmpop_ty)(asdl_seq_GET(
3366 e->v.Compare.ops, i - 1))));
3367 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3368 NEXT_BLOCK(c);
3369 if (i < (n - 1))
3370 VISIT(c, expr,
3371 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3372 }
3373 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3374 ADDOP_I(c, COMPARE_OP,
3375 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3376 if (n > 1) {
3377 basicblock *end = compiler_new_block(c);
3378 if (end == NULL)
3379 return 0;
3380 ADDOP_JREL(c, JUMP_FORWARD, end);
3381 compiler_use_next_block(c, cleanup);
3382 ADDOP(c, ROT_TWO);
3383 ADDOP(c, POP_TOP);
3384 compiler_use_next_block(c, end);
3385 }
3386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387}
3388
3389static int
3390compiler_call(struct compiler *c, expr_ty e)
3391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 VISIT(c, expr, e->v.Call.func);
3393 return compiler_call_helper(c, 0,
3394 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003395 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003396}
3397
Eric V. Smith235a6f02015-09-19 14:51:32 -04003398static int
3399compiler_joined_str(struct compiler *c, expr_ty e)
3400{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003401 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003402 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003403 return 1;
3404}
3405
Eric V. Smitha78c7952015-11-03 12:45:05 -05003406/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003407static int
3408compiler_formatted_value(struct compiler *c, expr_ty e)
3409{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003410 /* Our oparg encodes 2 pieces of information: the conversion
3411 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003412
Eric V. Smitha78c7952015-11-03 12:45:05 -05003413 Convert the conversion char to 2 bits:
3414 None: 000 0x0 FVC_NONE
3415 !s : 001 0x1 FVC_STR
3416 !r : 010 0x2 FVC_REPR
3417 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003418
Eric V. Smitha78c7952015-11-03 12:45:05 -05003419 next bit is whether or not we have a format spec:
3420 yes : 100 0x4
3421 no : 000 0x0
3422 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003423
Eric V. Smitha78c7952015-11-03 12:45:05 -05003424 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003425
Eric V. Smitha78c7952015-11-03 12:45:05 -05003426 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003427 VISIT(c, expr, e->v.FormattedValue.value);
3428
Eric V. Smitha78c7952015-11-03 12:45:05 -05003429 switch (e->v.FormattedValue.conversion) {
3430 case 's': oparg = FVC_STR; break;
3431 case 'r': oparg = FVC_REPR; break;
3432 case 'a': oparg = FVC_ASCII; break;
3433 case -1: oparg = FVC_NONE; break;
3434 default:
3435 PyErr_SetString(PyExc_SystemError,
3436 "Unrecognized conversion character");
3437 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003438 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003439 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003440 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003441 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003442 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003443 }
3444
Eric V. Smitha78c7952015-11-03 12:45:05 -05003445 /* And push our opcode and oparg */
3446 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003447 return 1;
3448}
3449
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003450static int
3451compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3452{
3453 Py_ssize_t i, n = end - begin;
3454 keyword_ty kw;
3455 PyObject *keys, *key;
3456 assert(n > 0);
3457 if (n > 1) {
3458 for (i = begin; i < end; i++) {
3459 kw = asdl_seq_GET(keywords, i);
3460 VISIT(c, expr, kw->value);
3461 }
3462 keys = PyTuple_New(n);
3463 if (keys == NULL) {
3464 return 0;
3465 }
3466 for (i = begin; i < end; i++) {
3467 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3468 Py_INCREF(key);
3469 PyTuple_SET_ITEM(keys, i - begin, key);
3470 }
3471 ADDOP_N(c, LOAD_CONST, keys, consts);
3472 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3473 }
3474 else {
3475 /* a for loop only executes once */
3476 for (i = begin; i < end; i++) {
3477 kw = asdl_seq_GET(keywords, i);
3478 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3479 VISIT(c, expr, kw->value);
3480 }
3481 ADDOP_I(c, BUILD_MAP, n);
3482 }
3483 return 1;
3484}
3485
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003486/* shared code between compiler_call and compiler_class */
3487static int
3488compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003489 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003490 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003491 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003494 Py_ssize_t nelts, i, nseen;
3495 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003496
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003497 /* the number of tuples and dictionaries on the stack */
3498 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3499
3500 nkw = 0;
3501 nseen = 0; /* the number of positional arguments on the stack */
3502 nelts = asdl_seq_LEN(args);
3503 for (i = 0; i < nelts; i++) {
3504 expr_ty elt = asdl_seq_GET(args, i);
3505 if (elt->kind == Starred_kind) {
3506 /* A star-arg. If we've seen positional arguments,
3507 pack the positional arguments into a
3508 tuple. */
3509 if (nseen) {
3510 ADDOP_I(c, BUILD_TUPLE, nseen);
3511 nseen = 0;
3512 nsubargs++;
3513 }
3514 VISIT(c, expr, elt->v.Starred.value);
3515 nsubargs++;
3516 }
3517 else if (nsubargs) {
3518 /* We've seen star-args already, so we
3519 count towards items-to-pack-into-tuple. */
3520 VISIT(c, expr, elt);
3521 nseen++;
3522 }
3523 else {
3524 /* Positional arguments before star-arguments
3525 are left on the stack. */
3526 VISIT(c, expr, elt);
3527 n++;
3528 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003530 if (nseen) {
3531 /* Pack up any trailing positional arguments. */
3532 ADDOP_I(c, BUILD_TUPLE, nseen);
3533 nsubargs++;
3534 }
3535 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537 if (nsubargs > 1) {
3538 /* If we ended up with more than one stararg, we need
3539 to concatenate them into a single sequence. */
3540 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3541 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003543
3544 /* Same dance again for keyword arguments */
3545 nseen = 0; /* the number of keyword arguments on the stack following */
3546 nelts = asdl_seq_LEN(keywords);
3547 for (i = 0; i < nelts; i++) {
3548 keyword_ty kw = asdl_seq_GET(keywords, i);
3549 if (kw->arg == NULL) {
3550 /* A keyword argument unpacking. */
3551 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003552 if (nsubkwargs) {
3553 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3554 return 0;
3555 nsubkwargs++;
3556 }
3557 else {
3558 Py_ssize_t j;
3559 for (j = 0; j < nseen; j++) {
3560 VISIT(c, keyword, asdl_seq_GET(keywords, j));
3561 }
3562 nkw = nseen;
3563 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003564 nseen = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003565 }
3566 VISIT(c, expr, kw->value);
3567 nsubkwargs++;
3568 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003569 else {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003570 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003571 }
3572 }
3573 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003574 if (nsubkwargs) {
3575 /* Pack up any trailing keyword arguments. */
3576 if (!compiler_subkwargs(c, keywords, nelts - nseen, nelts))
3577 return 0;
3578 nsubkwargs++;
3579 }
3580 else {
3581 VISIT_SEQ(c, keyword, keywords);
3582 nkw = nseen;
3583 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003584 }
3585 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003587 if (nsubkwargs > 1) {
3588 /* Pack it all up */
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03003589 int function_pos = n + (code & 1) + 2 * nkw + 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003590 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003593 assert(n < 1<<8);
3594 assert(nkw < 1<<24);
3595 n |= nkw << 8;
3596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 switch (code) {
3598 case 0:
3599 ADDOP_I(c, CALL_FUNCTION, n);
3600 break;
3601 case 1:
3602 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3603 break;
3604 case 2:
3605 ADDOP_I(c, CALL_FUNCTION_KW, n);
3606 break;
3607 case 3:
3608 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3609 break;
3610 }
3611 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
Nick Coghlan650f0d02007-04-15 12:05:43 +00003614
3615/* List and set comprehensions and generator expressions work by creating a
3616 nested function to perform the actual iteration. This means that the
3617 iteration variables don't leak into the current scope.
3618 The defined function is called immediately following its definition, with the
3619 result of that call being the result of the expression.
3620 The LC/SC version returns the populated container, while the GE version is
3621 flagged in symtable.c as a generator, so it returns the generator object
3622 when the function is called.
3623 This code *knows* that the loop cannot contain break, continue, or return,
3624 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3625
3626 Possible cleanups:
3627 - iterate over the generator sequence instead of using recursion
3628*/
3629
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631compiler_comprehension_generator(struct compiler *c,
3632 asdl_seq *generators, int gen_index,
3633 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 /* generate code for the iterator, then each of the ifs,
3636 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 comprehension_ty gen;
3639 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003640 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 start = compiler_new_block(c);
3643 skip = compiler_new_block(c);
3644 if_cleanup = compiler_new_block(c);
3645 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3648 anchor == NULL)
3649 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 if (gen_index == 0) {
3654 /* Receive outermost iter as an implicit argument */
3655 c->u->u_argcount = 1;
3656 ADDOP_I(c, LOAD_FAST, 0);
3657 }
3658 else {
3659 /* Sub-iter - calculate on the fly */
3660 VISIT(c, expr, gen->iter);
3661 ADDOP(c, GET_ITER);
3662 }
3663 compiler_use_next_block(c, start);
3664 ADDOP_JREL(c, FOR_ITER, anchor);
3665 NEXT_BLOCK(c);
3666 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 /* XXX this needs to be cleaned up...a lot! */
3669 n = asdl_seq_LEN(gen->ifs);
3670 for (i = 0; i < n; i++) {
3671 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3672 VISIT(c, expr, e);
3673 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3674 NEXT_BLOCK(c);
3675 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 if (++gen_index < asdl_seq_LEN(generators))
3678 if (!compiler_comprehension_generator(c,
3679 generators, gen_index,
3680 elt, val, type))
3681 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 /* only append after the last for generator */
3684 if (gen_index >= asdl_seq_LEN(generators)) {
3685 /* comprehension specific code */
3686 switch (type) {
3687 case COMP_GENEXP:
3688 VISIT(c, expr, elt);
3689 ADDOP(c, YIELD_VALUE);
3690 ADDOP(c, POP_TOP);
3691 break;
3692 case COMP_LISTCOMP:
3693 VISIT(c, expr, elt);
3694 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3695 break;
3696 case COMP_SETCOMP:
3697 VISIT(c, expr, elt);
3698 ADDOP_I(c, SET_ADD, gen_index + 1);
3699 break;
3700 case COMP_DICTCOMP:
3701 /* With 'd[k] = v', v is evaluated before k, so we do
3702 the same. */
3703 VISIT(c, expr, val);
3704 VISIT(c, expr, elt);
3705 ADDOP_I(c, MAP_ADD, gen_index + 1);
3706 break;
3707 default:
3708 return 0;
3709 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 compiler_use_next_block(c, skip);
3712 }
3713 compiler_use_next_block(c, if_cleanup);
3714 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3715 compiler_use_next_block(c, anchor);
3716
3717 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718}
3719
3720static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721compiler_comprehension(struct compiler *c, expr_ty e, int type,
3722 identifier name, asdl_seq *generators, expr_ty elt,
3723 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyCodeObject *co = NULL;
3726 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003727 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 outermost_iter = ((comprehension_ty)
3730 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003731
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003732 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3733 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 if (type != COMP_GENEXP) {
3737 int op;
3738 switch (type) {
3739 case COMP_LISTCOMP:
3740 op = BUILD_LIST;
3741 break;
3742 case COMP_SETCOMP:
3743 op = BUILD_SET;
3744 break;
3745 case COMP_DICTCOMP:
3746 op = BUILD_MAP;
3747 break;
3748 default:
3749 PyErr_Format(PyExc_SystemError,
3750 "unknown comprehension type %d", type);
3751 goto error_in_scope;
3752 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 ADDOP_I(c, op, 0);
3755 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 if (!compiler_comprehension_generator(c, generators, 0, elt,
3758 val, type))
3759 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (type != COMP_GENEXP) {
3762 ADDOP(c, RETURN_VALUE);
3763 }
3764
3765 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003766 qualname = c->u->u_qualname;
3767 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003769 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 goto error;
3771
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003772 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003774 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 Py_DECREF(co);
3776
3777 VISIT(c, expr, outermost_iter);
3778 ADDOP(c, GET_ITER);
3779 ADDOP_I(c, CALL_FUNCTION, 1);
3780 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003781error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003783error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003784 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 Py_XDECREF(co);
3786 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003787}
3788
3789static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790compiler_genexp(struct compiler *c, expr_ty e)
3791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 static identifier name;
3793 if (!name) {
3794 name = PyUnicode_FromString("<genexpr>");
3795 if (!name)
3796 return 0;
3797 }
3798 assert(e->kind == GeneratorExp_kind);
3799 return compiler_comprehension(c, e, COMP_GENEXP, name,
3800 e->v.GeneratorExp.generators,
3801 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802}
3803
3804static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003805compiler_listcomp(struct compiler *c, expr_ty e)
3806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 static identifier name;
3808 if (!name) {
3809 name = PyUnicode_FromString("<listcomp>");
3810 if (!name)
3811 return 0;
3812 }
3813 assert(e->kind == ListComp_kind);
3814 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3815 e->v.ListComp.generators,
3816 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003817}
3818
3819static int
3820compiler_setcomp(struct compiler *c, expr_ty e)
3821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 static identifier name;
3823 if (!name) {
3824 name = PyUnicode_FromString("<setcomp>");
3825 if (!name)
3826 return 0;
3827 }
3828 assert(e->kind == SetComp_kind);
3829 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3830 e->v.SetComp.generators,
3831 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003832}
3833
3834
3835static int
3836compiler_dictcomp(struct compiler *c, expr_ty e)
3837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 static identifier name;
3839 if (!name) {
3840 name = PyUnicode_FromString("<dictcomp>");
3841 if (!name)
3842 return 0;
3843 }
3844 assert(e->kind == DictComp_kind);
3845 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3846 e->v.DictComp.generators,
3847 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003848}
3849
3850
3851static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852compiler_visit_keyword(struct compiler *c, keyword_ty k)
3853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3855 VISIT(c, expr, k->value);
3856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857}
3858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 whether they are true or false.
3861
3862 Return values: 1 for true, 0 for false, -1 for non-constant.
3863 */
3864
3865static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003866expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 char *id;
3869 switch (e->kind) {
3870 case Ellipsis_kind:
3871 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003872 case Constant_kind:
3873 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 case Num_kind:
3875 return PyObject_IsTrue(e->v.Num.n);
3876 case Str_kind:
3877 return PyObject_IsTrue(e->v.Str.s);
3878 case Name_kind:
3879 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003881 if (id && strcmp(id, "__debug__") == 0)
3882 return !c->c_optimize;
3883 return -1;
3884 case NameConstant_kind: {
3885 PyObject *o = e->v.NameConstant.value;
3886 if (o == Py_None)
3887 return 0;
3888 else if (o == Py_True)
3889 return 1;
3890 else if (o == Py_False)
3891 return 0;
3892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 default:
3894 return -1;
3895 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896}
3897
Yury Selivanov75445082015-05-11 22:57:16 -04003898
3899/*
3900 Implements the async with statement.
3901
3902 The semantics outlined in that PEP are as follows:
3903
3904 async with EXPR as VAR:
3905 BLOCK
3906
3907 It is implemented roughly as:
3908
3909 context = EXPR
3910 exit = context.__aexit__ # not calling it
3911 value = await context.__aenter__()
3912 try:
3913 VAR = value # if VAR present in the syntax
3914 BLOCK
3915 finally:
3916 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003917 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003918 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003919 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003920 if not (await exit(*exc)):
3921 raise
3922 */
3923static int
3924compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3925{
3926 basicblock *block, *finally;
3927 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3928
3929 assert(s->kind == AsyncWith_kind);
3930
3931 block = compiler_new_block(c);
3932 finally = compiler_new_block(c);
3933 if (!block || !finally)
3934 return 0;
3935
3936 /* Evaluate EXPR */
3937 VISIT(c, expr, item->context_expr);
3938
3939 ADDOP(c, BEFORE_ASYNC_WITH);
3940 ADDOP(c, GET_AWAITABLE);
3941 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3942 ADDOP(c, YIELD_FROM);
3943
3944 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3945
3946 /* SETUP_ASYNC_WITH pushes a finally block. */
3947 compiler_use_next_block(c, block);
3948 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3949 return 0;
3950 }
3951
3952 if (item->optional_vars) {
3953 VISIT(c, expr, item->optional_vars);
3954 }
3955 else {
3956 /* Discard result from context.__aenter__() */
3957 ADDOP(c, POP_TOP);
3958 }
3959
3960 pos++;
3961 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3962 /* BLOCK code */
3963 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3964 else if (!compiler_async_with(c, s, pos))
3965 return 0;
3966
3967 /* End of try block; start the finally block */
3968 ADDOP(c, POP_BLOCK);
3969 compiler_pop_fblock(c, FINALLY_TRY, block);
3970
3971 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3972 compiler_use_next_block(c, finally);
3973 if (!compiler_push_fblock(c, FINALLY_END, finally))
3974 return 0;
3975
3976 /* Finally block starts; context.__exit__ is on the stack under
3977 the exception or return information. Just issue our magic
3978 opcode. */
3979 ADDOP(c, WITH_CLEANUP_START);
3980
3981 ADDOP(c, GET_AWAITABLE);
3982 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3983 ADDOP(c, YIELD_FROM);
3984
3985 ADDOP(c, WITH_CLEANUP_FINISH);
3986
3987 /* Finally block ends. */
3988 ADDOP(c, END_FINALLY);
3989 compiler_pop_fblock(c, FINALLY_END, finally);
3990 return 1;
3991}
3992
3993
Guido van Rossumc2e20742006-02-27 22:32:47 +00003994/*
3995 Implements the with statement from PEP 343.
3996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003998
3999 with EXPR as VAR:
4000 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001
Guido van Rossumc2e20742006-02-27 22:32:47 +00004002 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003
Thomas Wouters477c8d52006-05-27 19:21:47 +00004004 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004005 exit = context.__exit__ # not calling it
4006 value = context.__enter__()
4007 try:
4008 VAR = value # if VAR present in the syntax
4009 BLOCK
4010 finally:
4011 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004012 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004013 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004014 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004015 exit(*exc)
4016 */
4017static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004018compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004019{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004020 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004021 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004022
4023 assert(s->kind == With_kind);
4024
Guido van Rossumc2e20742006-02-27 22:32:47 +00004025 block = compiler_new_block(c);
4026 finally = compiler_new_block(c);
4027 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004028 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004029
Thomas Wouters477c8d52006-05-27 19:21:47 +00004030 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004031 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004032 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004033
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004034 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004035 compiler_use_next_block(c, block);
4036 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004037 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004038 }
4039
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004040 if (item->optional_vars) {
4041 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004042 }
4043 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004045 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004046 }
4047
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004048 pos++;
4049 if (pos == asdl_seq_LEN(s->v.With.items))
4050 /* BLOCK code */
4051 VISIT_SEQ(c, stmt, s->v.With.body)
4052 else if (!compiler_with(c, s, pos))
4053 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004054
4055 /* End of try block; start the finally block */
4056 ADDOP(c, POP_BLOCK);
4057 compiler_pop_fblock(c, FINALLY_TRY, block);
4058
4059 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4060 compiler_use_next_block(c, finally);
4061 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004062 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004063
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004064 /* Finally block starts; context.__exit__ is on the stack under
4065 the exception or return information. Just issue our magic
4066 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004067 ADDOP(c, WITH_CLEANUP_START);
4068 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004069
4070 /* Finally block ends. */
4071 ADDOP(c, END_FINALLY);
4072 compiler_pop_fblock(c, FINALLY_END, finally);
4073 return 1;
4074}
4075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076static int
4077compiler_visit_expr(struct compiler *c, expr_ty e)
4078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 /* If expr e has a different line number than the last expr/stmt,
4080 set a new line number for the next instruction.
4081 */
4082 if (e->lineno > c->u->u_lineno) {
4083 c->u->u_lineno = e->lineno;
4084 c->u->u_lineno_set = 0;
4085 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004086 /* Updating the column offset is always harmless. */
4087 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 switch (e->kind) {
4089 case BoolOp_kind:
4090 return compiler_boolop(c, e);
4091 case BinOp_kind:
4092 VISIT(c, expr, e->v.BinOp.left);
4093 VISIT(c, expr, e->v.BinOp.right);
4094 ADDOP(c, binop(c, e->v.BinOp.op));
4095 break;
4096 case UnaryOp_kind:
4097 VISIT(c, expr, e->v.UnaryOp.operand);
4098 ADDOP(c, unaryop(e->v.UnaryOp.op));
4099 break;
4100 case Lambda_kind:
4101 return compiler_lambda(c, e);
4102 case IfExp_kind:
4103 return compiler_ifexp(c, e);
4104 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004105 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004107 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 case GeneratorExp_kind:
4109 return compiler_genexp(c, e);
4110 case ListComp_kind:
4111 return compiler_listcomp(c, e);
4112 case SetComp_kind:
4113 return compiler_setcomp(c, e);
4114 case DictComp_kind:
4115 return compiler_dictcomp(c, e);
4116 case Yield_kind:
4117 if (c->u->u_ste->ste_type != FunctionBlock)
4118 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004119 if (e->v.Yield.value) {
4120 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 }
4122 else {
4123 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4124 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004125 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004127 case YieldFrom_kind:
4128 if (c->u->u_ste->ste_type != FunctionBlock)
4129 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004130
4131 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4132 return compiler_error(c, "'yield from' inside async function");
4133
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004134 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004135 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004136 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4137 ADDOP(c, YIELD_FROM);
4138 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004139 case Await_kind:
4140 if (c->u->u_ste->ste_type != FunctionBlock)
4141 return compiler_error(c, "'await' outside function");
4142
Yury Selivanov9dec0352015-06-30 12:49:04 -04004143 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
4144 return compiler_error(
4145 c, "'await' expressions in comprehensions are not supported");
4146
Yury Selivanov75445082015-05-11 22:57:16 -04004147 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
4148 return compiler_error(c, "'await' outside async function");
4149
4150 VISIT(c, expr, e->v.Await.value);
4151 ADDOP(c, GET_AWAITABLE);
4152 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4153 ADDOP(c, YIELD_FROM);
4154 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 case Compare_kind:
4156 return compiler_compare(c, e);
4157 case Call_kind:
4158 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004159 case Constant_kind:
4160 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4161 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 case Num_kind:
4163 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4164 break;
4165 case Str_kind:
4166 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4167 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168 case JoinedStr_kind:
4169 return compiler_joined_str(c, e);
4170 case FormattedValue_kind:
4171 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 case Bytes_kind:
4173 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4174 break;
4175 case Ellipsis_kind:
4176 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4177 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004178 case NameConstant_kind:
4179 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4180 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 /* The following exprs can be assignment targets. */
4182 case Attribute_kind:
4183 if (e->v.Attribute.ctx != AugStore)
4184 VISIT(c, expr, e->v.Attribute.value);
4185 switch (e->v.Attribute.ctx) {
4186 case AugLoad:
4187 ADDOP(c, DUP_TOP);
4188 /* Fall through to load */
4189 case Load:
4190 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4191 break;
4192 case AugStore:
4193 ADDOP(c, ROT_TWO);
4194 /* Fall through to save */
4195 case Store:
4196 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4197 break;
4198 case Del:
4199 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4200 break;
4201 case Param:
4202 default:
4203 PyErr_SetString(PyExc_SystemError,
4204 "param invalid in attribute expression");
4205 return 0;
4206 }
4207 break;
4208 case Subscript_kind:
4209 switch (e->v.Subscript.ctx) {
4210 case AugLoad:
4211 VISIT(c, expr, e->v.Subscript.value);
4212 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4213 break;
4214 case Load:
4215 VISIT(c, expr, e->v.Subscript.value);
4216 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4217 break;
4218 case AugStore:
4219 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4220 break;
4221 case Store:
4222 VISIT(c, expr, e->v.Subscript.value);
4223 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4224 break;
4225 case Del:
4226 VISIT(c, expr, e->v.Subscript.value);
4227 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4228 break;
4229 case Param:
4230 default:
4231 PyErr_SetString(PyExc_SystemError,
4232 "param invalid in subscript expression");
4233 return 0;
4234 }
4235 break;
4236 case Starred_kind:
4237 switch (e->v.Starred.ctx) {
4238 case Store:
4239 /* In all legitimate cases, the Starred node was already replaced
4240 * by compiler_list/compiler_tuple. XXX: is that okay? */
4241 return compiler_error(c,
4242 "starred assignment target must be in a list or tuple");
4243 default:
4244 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004245 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 }
4247 break;
4248 case Name_kind:
4249 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4250 /* child nodes of List and Tuple will have expr_context set */
4251 case List_kind:
4252 return compiler_list(c, e);
4253 case Tuple_kind:
4254 return compiler_tuple(c, e);
4255 }
4256 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257}
4258
4259static int
4260compiler_augassign(struct compiler *c, stmt_ty s)
4261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 expr_ty e = s->v.AugAssign.target;
4263 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 switch (e->kind) {
4268 case Attribute_kind:
4269 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4270 AugLoad, e->lineno, e->col_offset, c->c_arena);
4271 if (auge == NULL)
4272 return 0;
4273 VISIT(c, expr, auge);
4274 VISIT(c, expr, s->v.AugAssign.value);
4275 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4276 auge->v.Attribute.ctx = AugStore;
4277 VISIT(c, expr, auge);
4278 break;
4279 case Subscript_kind:
4280 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4281 AugLoad, e->lineno, e->col_offset, c->c_arena);
4282 if (auge == NULL)
4283 return 0;
4284 VISIT(c, expr, auge);
4285 VISIT(c, expr, s->v.AugAssign.value);
4286 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4287 auge->v.Subscript.ctx = AugStore;
4288 VISIT(c, expr, auge);
4289 break;
4290 case Name_kind:
4291 if (!compiler_nameop(c, e->v.Name.id, Load))
4292 return 0;
4293 VISIT(c, expr, s->v.AugAssign.value);
4294 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4295 return compiler_nameop(c, e->v.Name.id, Store);
4296 default:
4297 PyErr_Format(PyExc_SystemError,
4298 "invalid node type (%d) for augmented assignment",
4299 e->kind);
4300 return 0;
4301 }
4302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004303}
4304
4305static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004306check_ann_expr(struct compiler *c, expr_ty e)
4307{
4308 VISIT(c, expr, e);
4309 ADDOP(c, POP_TOP);
4310 return 1;
4311}
4312
4313static int
4314check_annotation(struct compiler *c, stmt_ty s)
4315{
4316 /* Annotations are only evaluated in a module or class. */
4317 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4318 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4319 return check_ann_expr(c, s->v.AnnAssign.annotation);
4320 }
4321 return 1;
4322}
4323
4324static int
4325check_ann_slice(struct compiler *c, slice_ty sl)
4326{
4327 switch(sl->kind) {
4328 case Index_kind:
4329 return check_ann_expr(c, sl->v.Index.value);
4330 case Slice_kind:
4331 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4332 return 0;
4333 }
4334 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4335 return 0;
4336 }
4337 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4338 return 0;
4339 }
4340 break;
4341 default:
4342 PyErr_SetString(PyExc_SystemError,
4343 "unexpected slice kind");
4344 return 0;
4345 }
4346 return 1;
4347}
4348
4349static int
4350check_ann_subscr(struct compiler *c, slice_ty sl)
4351{
4352 /* We check that everything in a subscript is defined at runtime. */
4353 Py_ssize_t i, n;
4354
4355 switch (sl->kind) {
4356 case Index_kind:
4357 case Slice_kind:
4358 if (!check_ann_slice(c, sl)) {
4359 return 0;
4360 }
4361 break;
4362 case ExtSlice_kind:
4363 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4364 for (i = 0; i < n; i++) {
4365 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4366 switch (subsl->kind) {
4367 case Index_kind:
4368 case Slice_kind:
4369 if (!check_ann_slice(c, subsl)) {
4370 return 0;
4371 }
4372 break;
4373 case ExtSlice_kind:
4374 default:
4375 PyErr_SetString(PyExc_SystemError,
4376 "extended slice invalid in nested slice");
4377 return 0;
4378 }
4379 }
4380 break;
4381 default:
4382 PyErr_Format(PyExc_SystemError,
4383 "invalid subscript kind %d", sl->kind);
4384 return 0;
4385 }
4386 return 1;
4387}
4388
4389static int
4390compiler_annassign(struct compiler *c, stmt_ty s)
4391{
4392 expr_ty targ = s->v.AnnAssign.target;
4393
4394 assert(s->kind == AnnAssign_kind);
4395
4396 /* We perform the actual assignment first. */
4397 if (s->v.AnnAssign.value) {
4398 VISIT(c, expr, s->v.AnnAssign.value);
4399 VISIT(c, expr, targ);
4400 }
4401 switch (targ->kind) {
4402 case Name_kind:
4403 /* If we have a simple name in a module or class, store annotation. */
4404 if (s->v.AnnAssign.simple &&
4405 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4406 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
4407 VISIT(c, expr, s->v.AnnAssign.annotation);
4408 ADDOP_O(c, STORE_ANNOTATION, targ->v.Name.id, names)
4409 }
4410 break;
4411 case Attribute_kind:
4412 if (!s->v.AnnAssign.value &&
4413 !check_ann_expr(c, targ->v.Attribute.value)) {
4414 return 0;
4415 }
4416 break;
4417 case Subscript_kind:
4418 if (!s->v.AnnAssign.value &&
4419 (!check_ann_expr(c, targ->v.Subscript.value) ||
4420 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4421 return 0;
4422 }
4423 break;
4424 default:
4425 PyErr_Format(PyExc_SystemError,
4426 "invalid node type (%d) for annotated assignment",
4427 targ->kind);
4428 return 0;
4429 }
4430 /* Annotation is evaluated last. */
4431 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4432 return 0;
4433 }
4434 return 1;
4435}
4436
4437static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 struct fblockinfo *f;
4441 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004442 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 "too many statically nested blocks");
4444 return 0;
4445 }
4446 f = &c->u->u_fblock[c->u->u_nfblocks++];
4447 f->fb_type = t;
4448 f->fb_block = b;
4449 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004450}
4451
4452static void
4453compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 struct compiler_unit *u = c->u;
4456 assert(u->u_nfblocks > 0);
4457 u->u_nfblocks--;
4458 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4459 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004460}
4461
Thomas Wouters89f507f2006-12-13 04:49:30 +00004462static int
4463compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 int i;
4465 struct compiler_unit *u = c->u;
4466 for (i = 0; i < u->u_nfblocks; ++i) {
4467 if (u->u_fblock[i].fb_type == LOOP)
4468 return 1;
4469 }
4470 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004471}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004472/* Raises a SyntaxError and returns 0.
4473 If something goes wrong, a different exception may be raised.
4474*/
4475
4476static int
4477compiler_error(struct compiler *c, const char *errstr)
4478{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004479 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004481
Victor Stinner14e461d2013-08-26 22:28:21 +02004482 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 if (!loc) {
4484 Py_INCREF(Py_None);
4485 loc = Py_None;
4486 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004487 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004488 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 if (!u)
4490 goto exit;
4491 v = Py_BuildValue("(zO)", errstr, u);
4492 if (!v)
4493 goto exit;
4494 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004495 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 Py_DECREF(loc);
4497 Py_XDECREF(u);
4498 Py_XDECREF(v);
4499 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
4502static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503compiler_handle_subscr(struct compiler *c, const char *kind,
4504 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 /* XXX this code is duplicated */
4509 switch (ctx) {
4510 case AugLoad: /* fall through to Load */
4511 case Load: op = BINARY_SUBSCR; break;
4512 case AugStore:/* fall through to Store */
4513 case Store: op = STORE_SUBSCR; break;
4514 case Del: op = DELETE_SUBSCR; break;
4515 case Param:
4516 PyErr_Format(PyExc_SystemError,
4517 "invalid %s kind %d in subscript\n",
4518 kind, ctx);
4519 return 0;
4520 }
4521 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004522 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 }
4524 else if (ctx == AugStore) {
4525 ADDOP(c, ROT_THREE);
4526 }
4527 ADDOP(c, op);
4528 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004529}
4530
4531static int
4532compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 int n = 2;
4535 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 /* only handles the cases where BUILD_SLICE is emitted */
4538 if (s->v.Slice.lower) {
4539 VISIT(c, expr, s->v.Slice.lower);
4540 }
4541 else {
4542 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 if (s->v.Slice.upper) {
4546 VISIT(c, expr, s->v.Slice.upper);
4547 }
4548 else {
4549 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4550 }
4551
4552 if (s->v.Slice.step) {
4553 n++;
4554 VISIT(c, expr, s->v.Slice.step);
4555 }
4556 ADDOP_I(c, BUILD_SLICE, n);
4557 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004558}
4559
4560static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4562 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 switch (s->kind) {
4565 case Slice_kind:
4566 return compiler_slice(c, s, ctx);
4567 case Index_kind:
4568 VISIT(c, expr, s->v.Index.value);
4569 break;
4570 case ExtSlice_kind:
4571 default:
4572 PyErr_SetString(PyExc_SystemError,
4573 "extended slice invalid in nested slice");
4574 return 0;
4575 }
4576 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004577}
4578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004579static int
4580compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 char * kindname = NULL;
4583 switch (s->kind) {
4584 case Index_kind:
4585 kindname = "index";
4586 if (ctx != AugStore) {
4587 VISIT(c, expr, s->v.Index.value);
4588 }
4589 break;
4590 case Slice_kind:
4591 kindname = "slice";
4592 if (ctx != AugStore) {
4593 if (!compiler_slice(c, s, ctx))
4594 return 0;
4595 }
4596 break;
4597 case ExtSlice_kind:
4598 kindname = "extended slice";
4599 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004600 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 for (i = 0; i < n; i++) {
4602 slice_ty sub = (slice_ty)asdl_seq_GET(
4603 s->v.ExtSlice.dims, i);
4604 if (!compiler_visit_nested_slice(c, sub, ctx))
4605 return 0;
4606 }
4607 ADDOP_I(c, BUILD_TUPLE, n);
4608 }
4609 break;
4610 default:
4611 PyErr_Format(PyExc_SystemError,
4612 "invalid subscript kind %d", s->kind);
4613 return 0;
4614 }
4615 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004616}
4617
Thomas Wouters89f507f2006-12-13 04:49:30 +00004618/* End of the compiler section, beginning of the assembler section */
4619
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004620/* do depth-first search of basic block graph, starting with block.
4621 post records the block indices in post-order.
4622
4623 XXX must handle implicit jumps from one block to next
4624*/
4625
Thomas Wouters89f507f2006-12-13 04:49:30 +00004626struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 PyObject *a_bytecode; /* string containing bytecode */
4628 int a_offset; /* offset into bytecode */
4629 int a_nblocks; /* number of reachable blocks */
4630 basicblock **a_postorder; /* list of blocks in dfs postorder */
4631 PyObject *a_lnotab; /* string containing lnotab */
4632 int a_lnotab_off; /* offset into lnotab */
4633 int a_lineno; /* last lineno of emitted instruction */
4634 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004635};
4636
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004637static void
4638dfs(struct compiler *c, basicblock *b, struct assembler *a)
4639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 int i;
4641 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (b->b_seen)
4644 return;
4645 b->b_seen = 1;
4646 if (b->b_next != NULL)
4647 dfs(c, b->b_next, a);
4648 for (i = 0; i < b->b_iused; i++) {
4649 instr = &b->b_instr[i];
4650 if (instr->i_jrel || instr->i_jabs)
4651 dfs(c, instr->i_target, a);
4652 }
4653 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654}
4655
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004656static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004657stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4658{
Larry Hastings3a907972013-11-23 14:49:22 -08004659 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 struct instr *instr;
4661 if (b->b_seen || b->b_startdepth >= depth)
4662 return maxdepth;
4663 b->b_seen = 1;
4664 b->b_startdepth = depth;
4665 for (i = 0; i < b->b_iused; i++) {
4666 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004667 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4668 if (effect == PY_INVALID_STACK_EFFECT) {
4669 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4670 Py_FatalError("PyCompile_OpcodeStackEffect()");
4671 }
4672 depth += effect;
4673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (depth > maxdepth)
4675 maxdepth = depth;
4676 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4677 if (instr->i_jrel || instr->i_jabs) {
4678 target_depth = depth;
4679 if (instr->i_opcode == FOR_ITER) {
4680 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004681 }
4682 else if (instr->i_opcode == SETUP_FINALLY ||
4683 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 target_depth = depth+3;
4685 if (target_depth > maxdepth)
4686 maxdepth = target_depth;
4687 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004688 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4689 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4690 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 maxdepth = stackdepth_walk(c, instr->i_target,
4692 target_depth, maxdepth);
4693 if (instr->i_opcode == JUMP_ABSOLUTE ||
4694 instr->i_opcode == JUMP_FORWARD) {
4695 goto out; /* remaining code is dead */
4696 }
4697 }
4698 }
4699 if (b->b_next)
4700 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004701out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 b->b_seen = 0;
4703 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004704}
4705
4706/* Find the flow path that needs the largest stack. We assume that
4707 * cycles in the flow graph have no net effect on the stack depth.
4708 */
4709static int
4710stackdepth(struct compiler *c)
4711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 basicblock *b, *entryblock;
4713 entryblock = NULL;
4714 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4715 b->b_seen = 0;
4716 b->b_startdepth = INT_MIN;
4717 entryblock = b;
4718 }
4719 if (!entryblock)
4720 return 0;
4721 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004722}
4723
4724static int
4725assemble_init(struct assembler *a, int nblocks, int firstlineno)
4726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 memset(a, 0, sizeof(struct assembler));
4728 a->a_lineno = firstlineno;
4729 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4730 if (!a->a_bytecode)
4731 return 0;
4732 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4733 if (!a->a_lnotab)
4734 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004735 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 PyErr_NoMemory();
4737 return 0;
4738 }
4739 a->a_postorder = (basicblock **)PyObject_Malloc(
4740 sizeof(basicblock *) * nblocks);
4741 if (!a->a_postorder) {
4742 PyErr_NoMemory();
4743 return 0;
4744 }
4745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004746}
4747
4748static void
4749assemble_free(struct assembler *a)
4750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 Py_XDECREF(a->a_bytecode);
4752 Py_XDECREF(a->a_lnotab);
4753 if (a->a_postorder)
4754 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004755}
4756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004757static int
4758blocksize(basicblock *b)
4759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 int i;
4761 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004764 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004766}
4767
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004768/* Appends a pair to the end of the line number table, a_lnotab, representing
4769 the instruction's bytecode offset and line number. See
4770 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004771
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004772static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004776 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 d_bytecode = a->a_offset - a->a_lineno_off;
4780 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004782 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 if(d_bytecode == 0 && d_lineno == 0)
4785 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 if (d_bytecode > 255) {
4788 int j, nbytes, ncodes = d_bytecode / 255;
4789 nbytes = a->a_lnotab_off + 2 * ncodes;
4790 len = PyBytes_GET_SIZE(a->a_lnotab);
4791 if (nbytes >= len) {
4792 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4793 len = nbytes;
4794 else if (len <= INT_MAX / 2)
4795 len *= 2;
4796 else {
4797 PyErr_NoMemory();
4798 return 0;
4799 }
4800 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4801 return 0;
4802 }
4803 lnotab = (unsigned char *)
4804 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4805 for (j = 0; j < ncodes; j++) {
4806 *lnotab++ = 255;
4807 *lnotab++ = 0;
4808 }
4809 d_bytecode -= ncodes * 255;
4810 a->a_lnotab_off += ncodes * 2;
4811 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004812 assert(0 <= d_bytecode && d_bytecode <= 255);
4813
4814 if (d_lineno < -128 || 127 < d_lineno) {
4815 int j, nbytes, ncodes, k;
4816 if (d_lineno < 0) {
4817 k = -128;
4818 /* use division on positive numbers */
4819 ncodes = (-d_lineno) / 128;
4820 }
4821 else {
4822 k = 127;
4823 ncodes = d_lineno / 127;
4824 }
4825 d_lineno -= ncodes * k;
4826 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 nbytes = a->a_lnotab_off + 2 * ncodes;
4828 len = PyBytes_GET_SIZE(a->a_lnotab);
4829 if (nbytes >= len) {
4830 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4831 len = nbytes;
4832 else if (len <= INT_MAX / 2)
4833 len *= 2;
4834 else {
4835 PyErr_NoMemory();
4836 return 0;
4837 }
4838 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4839 return 0;
4840 }
4841 lnotab = (unsigned char *)
4842 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4843 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004844 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 d_bytecode = 0;
4846 for (j = 1; j < ncodes; j++) {
4847 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004848 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 a->a_lnotab_off += ncodes * 2;
4851 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004852 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 len = PyBytes_GET_SIZE(a->a_lnotab);
4855 if (a->a_lnotab_off + 2 >= len) {
4856 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4857 return 0;
4858 }
4859 lnotab = (unsigned char *)
4860 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 a->a_lnotab_off += 2;
4863 if (d_bytecode) {
4864 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004865 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 }
4867 else { /* First line of a block; def stmt, etc. */
4868 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004869 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 }
4871 a->a_lineno = i->i_lineno;
4872 a->a_lineno_off = a->a_offset;
4873 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004874}
4875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004876/* assemble_emit()
4877 Extend the bytecode with a new instruction.
4878 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004879*/
4880
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004881static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004882assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004883{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004884 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4886 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004887
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004888 arg = i->i_oparg;
4889 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 if (i->i_lineno && !assemble_lnotab(a, i))
4891 return 0;
4892 if (a->a_offset + size >= len) {
4893 if (len > PY_SSIZE_T_MAX / 2)
4894 return 0;
4895 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4896 return 0;
4897 }
4898 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4899 a->a_offset += size;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004900 write_op_arg((unsigned char*)code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004902}
4903
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004904static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004905assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004908 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 /* Compute the size of each block and fixup jump args.
4912 Replace block pointer with position in bytecode. */
4913 do {
4914 totsize = 0;
4915 for (i = a->a_nblocks - 1; i >= 0; i--) {
4916 b = a->a_postorder[i];
4917 bsize = blocksize(b);
4918 b->b_offset = totsize;
4919 totsize += bsize;
4920 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004921 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4923 bsize = b->b_offset;
4924 for (i = 0; i < b->b_iused; i++) {
4925 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004926 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 /* Relative jumps are computed relative to
4928 the instruction pointer after fetching
4929 the jump instruction.
4930 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004931 bsize += isize;
4932 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004934 if (instr->i_jrel) {
4935 instr->i_oparg -= bsize;
4936 }
4937 if (instrsize(instr->i_oparg) != isize) {
4938 extended_arg_recompile = 1;
4939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 }
4942 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 /* XXX: This is an awful hack that could hurt performance, but
4945 on the bright side it should work until we come up
4946 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 The issue is that in the first loop blocksize() is called
4949 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004950 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 So we loop until we stop seeing new EXTENDED_ARGs.
4954 The only EXTENDED_ARGs that could be popping up are
4955 ones in jump instructions. So this should converge
4956 fairly quickly.
4957 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004958 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004959}
4960
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004961static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004962dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 PyObject *tuple, *k, *v;
4965 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 tuple = PyTuple_New(size);
4968 if (tuple == NULL)
4969 return NULL;
4970 while (PyDict_Next(dict, &pos, &k, &v)) {
4971 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004972 /* The keys of the dictionary are tuples. (see compiler_add_o
4973 * and _PyCode_ConstantKey). The object we want is always second,
4974 * though. */
4975 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 Py_INCREF(k);
4977 assert((i - offset) < size);
4978 assert((i - offset) >= 0);
4979 PyTuple_SET_ITEM(tuple, i - offset, k);
4980 }
4981 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004982}
4983
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004984static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004985compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004988 int flags = 0;
4989 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004991 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 if (ste->ste_nested)
4993 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07004994 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07004996 if (!ste->ste_generator && ste->ste_coroutine)
4997 flags |= CO_COROUTINE;
4998 if (ste->ste_generator && ste->ste_coroutine)
4999 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 if (ste->ste_varargs)
5001 flags |= CO_VARARGS;
5002 if (ste->ste_varkeywords)
5003 flags |= CO_VARKEYWORDS;
5004 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 /* (Only) inherit compilerflags in PyCF_MASK */
5007 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 n = PyDict_Size(c->u->u_freevars);
5010 if (n < 0)
5011 return -1;
5012 if (n == 0) {
5013 n = PyDict_Size(c->u->u_cellvars);
5014 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01005015 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005017 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 }
5019 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005022}
5023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005024static PyCodeObject *
5025makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 PyObject *tmp;
5028 PyCodeObject *co = NULL;
5029 PyObject *consts = NULL;
5030 PyObject *names = NULL;
5031 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 PyObject *name = NULL;
5033 PyObject *freevars = NULL;
5034 PyObject *cellvars = NULL;
5035 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005036 Py_ssize_t nlocals;
5037 int nlocals_int;
5038 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005039 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 tmp = dict_keys_inorder(c->u->u_consts, 0);
5042 if (!tmp)
5043 goto error;
5044 consts = PySequence_List(tmp); /* optimize_code requires a list */
5045 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 names = dict_keys_inorder(c->u->u_names, 0);
5048 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5049 if (!consts || !names || !varnames)
5050 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5053 if (!cellvars)
5054 goto error;
5055 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5056 if (!freevars)
5057 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005060 assert(nlocals < INT_MAX);
5061 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 flags = compute_code_flags(c);
5064 if (flags < 0)
5065 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5068 if (!bytecode)
5069 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5072 if (!tmp)
5073 goto error;
5074 Py_DECREF(consts);
5075 consts = tmp;
5076
Victor Stinnerf8e32212013-11-19 23:56:34 +01005077 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5078 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5079 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005080 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 bytecode, consts, names, varnames,
5082 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005083 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 c->u->u_firstlineno,
5085 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 Py_XDECREF(consts);
5088 Py_XDECREF(names);
5089 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 Py_XDECREF(name);
5091 Py_XDECREF(freevars);
5092 Py_XDECREF(cellvars);
5093 Py_XDECREF(bytecode);
5094 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005095}
5096
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005097
5098/* For debugging purposes only */
5099#if 0
5100static void
5101dump_instr(const struct instr *i)
5102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 const char *jrel = i->i_jrel ? "jrel " : "";
5104 const char *jabs = i->i_jabs ? "jabs " : "";
5105 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005108 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5112 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005113}
5114
5115static void
5116dump_basicblock(const basicblock *b)
5117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 const char *seen = b->b_seen ? "seen " : "";
5119 const char *b_return = b->b_return ? "return " : "";
5120 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5121 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5122 if (b->b_instr) {
5123 int i;
5124 for (i = 0; i < b->b_iused; i++) {
5125 fprintf(stderr, " [%02d] ", i);
5126 dump_instr(b->b_instr + i);
5127 }
5128 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005129}
5130#endif
5131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005132static PyCodeObject *
5133assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 basicblock *b, *entryblock;
5136 struct assembler a;
5137 int i, j, nblocks;
5138 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 /* Make sure every block that falls off the end returns None.
5141 XXX NEXT_BLOCK() isn't quite right, because if the last
5142 block ends with a jump or return b_next shouldn't set.
5143 */
5144 if (!c->u->u_curblock->b_return) {
5145 NEXT_BLOCK(c);
5146 if (addNone)
5147 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5148 ADDOP(c, RETURN_VALUE);
5149 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 nblocks = 0;
5152 entryblock = NULL;
5153 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5154 nblocks++;
5155 entryblock = b;
5156 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 /* Set firstlineno if it wasn't explicitly set. */
5159 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005160 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5162 else
5163 c->u->u_firstlineno = 1;
5164 }
5165 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5166 goto error;
5167 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 /* Can't modify the bytecode after computing jump offsets. */
5170 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 /* Emit code in reverse postorder from dfs. */
5173 for (i = a.a_nblocks - 1; i >= 0; i--) {
5174 b = a.a_postorder[i];
5175 for (j = 0; j < b->b_iused; j++)
5176 if (!assemble_emit(&a, &b->b_instr[j]))
5177 goto error;
5178 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5181 goto error;
5182 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
5183 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005186 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 assemble_free(&a);
5188 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005189}
Georg Brandl8334fd92010-12-04 10:26:46 +00005190
5191#undef PyAST_Compile
5192PyAPI_FUNC(PyCodeObject *)
5193PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5194 PyArena *arena)
5195{
5196 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5197}