blob: 687b7506bf70e946c5818bf7c9369952e2987da1 [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);
182static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184
185static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189/* Returns true if there is a loop on the fblock stack. */
190static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
192static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000193static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500195static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400196static int compiler_async_with(struct compiler *, stmt_ty, int);
197static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400200 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500201static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400202static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400207#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100389 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100395 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100417dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100451 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100458 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinner976bb402016-03-23 11:36:19 +0100479 assert((Py_uintptr_t)block != 0xcbcbcbcbU);
480 assert((Py_uintptr_t)block != 0xfbfbfbfbU);
481 assert((Py_uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100525 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000551 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100562 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100623
624 block = compiler_new_block(c);
625 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400629 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
630 if (!compiler_set_qualname(c))
631 return 0;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635}
636
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000637static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638compiler_exit_scope(struct compiler *c)
639{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100640 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 c->c_nestlevel--;
644 compiler_unit_free(c->u);
645 /* Restore c->u to the parent unit. */
646 n = PyList_GET_SIZE(c->c_stack) - 1;
647 if (n >= 0) {
648 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400649 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 assert(c->u);
651 /* we are deleting from a list so this really shouldn't fail */
652 if (PySequence_DelItem(c->c_stack, n) < 0)
653 Py_FatalError("compiler_exit_scope()");
654 compiler_unit_check(c->u);
655 }
656 else
657 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659}
660
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400661static int
662compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100663{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 _Py_static_string(dot_locals, ".<locals>");
666 Py_ssize_t stack_size;
667 struct compiler_unit *u = c->u;
668 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400672 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 if (stack_size > 1) {
674 int scope, force_global = 0;
675 struct compiler_unit *parent;
676 PyObject *mangled, *capsule;
677
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400678 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400679 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(parent);
681
Yury Selivanov75445082015-05-11 22:57:16 -0400682 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
683 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
684 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(u->u_name);
686 mangled = _Py_Mangle(parent->u_private, u->u_name);
687 if (!mangled)
688 return 0;
689 scope = PyST_GetScope(parent->u_ste, mangled);
690 Py_DECREF(mangled);
691 assert(scope != GLOBAL_IMPLICIT);
692 if (scope == GLOBAL_EXPLICIT)
693 force_global = 1;
694 }
695
696 if (!force_global) {
697 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400698 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
700 dot_locals_str = _PyUnicode_FromId(&dot_locals);
701 if (dot_locals_str == NULL)
702 return 0;
703 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
704 if (base == NULL)
705 return 0;
706 }
707 else {
708 Py_INCREF(parent->u_qualname);
709 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100711 }
712 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 if (base != NULL) {
715 dot_str = _PyUnicode_FromId(&dot);
716 if (dot_str == NULL) {
717 Py_DECREF(base);
718 return 0;
719 }
720 name = PyUnicode_Concat(base, dot_str);
721 Py_DECREF(base);
722 if (name == NULL)
723 return 0;
724 PyUnicode_Append(&name, u->u_name);
725 if (name == NULL)
726 return 0;
727 }
728 else {
729 Py_INCREF(u->u_name);
730 name = u->u_name;
731 }
732 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100733
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100735}
736
Eric V. Smith235a6f02015-09-19 14:51:32 -0400737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000738/* Allocate a new block and return a pointer to it.
739 Returns NULL on error.
740*/
741
742static basicblock *
743compiler_new_block(struct compiler *c)
744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 basicblock *b;
746 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 u = c->u;
749 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
750 if (b == NULL) {
751 PyErr_NoMemory();
752 return NULL;
753 }
754 memset((void *)b, 0, sizeof(basicblock));
755 /* Extend the singly linked list of blocks with new block. */
756 b->b_list = u->u_blocks;
757 u->u_blocks = b;
758 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759}
760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762compiler_next_block(struct compiler *c)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 basicblock *block = compiler_new_block(c);
765 if (block == NULL)
766 return NULL;
767 c->u->u_curblock->b_next = block;
768 c->u->u_curblock = block;
769 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
772static basicblock *
773compiler_use_next_block(struct compiler *c, basicblock *block)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 assert(block != NULL);
776 c->u->u_curblock->b_next = block;
777 c->u->u_curblock = block;
778 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
781/* Returns the offset of the next instruction in the current block's
782 b_instr array. Resizes the b_instr as necessary.
783 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000784*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786static int
787compiler_next_instr(struct compiler *c, basicblock *b)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(b != NULL);
790 if (b->b_instr == NULL) {
791 b->b_instr = (struct instr *)PyObject_Malloc(
792 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
793 if (b->b_instr == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 b->b_ialloc = DEFAULT_BLOCK_SIZE;
798 memset((char *)b->b_instr, 0,
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 }
801 else if (b->b_iused == b->b_ialloc) {
802 struct instr *tmp;
803 size_t oldsize, newsize;
804 oldsize = b->b_ialloc * sizeof(struct instr);
805 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (oldsize > (PY_SIZE_MAX >> 1)) {
808 PyErr_NoMemory();
809 return -1;
810 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (newsize == 0) {
813 PyErr_NoMemory();
814 return -1;
815 }
816 b->b_ialloc <<= 1;
817 tmp = (struct instr *)PyObject_Realloc(
818 (void *)b->b_instr, newsize);
819 if (tmp == NULL) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_instr = tmp;
824 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
825 }
826 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827}
828
Christian Heimes2202f872008-02-06 14:31:34 +0000829/* Set the i_lineno member of the instruction at offset off if the
830 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 already been set. If it has been set, the call has no effect.
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833 The line number is reset in the following cases:
834 - when entering a new scope
835 - on each statement
836 - on each expression that start a new line
837 - before the "except" clause
838 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841static void
842compiler_set_lineno(struct compiler *c, int off)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 basicblock *b;
845 if (c->u->u_lineno_set)
846 return;
847 c->u->u_lineno_set = 1;
848 b = c->u->u_curblock;
849 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850}
851
Larry Hastings3a907972013-11-23 14:49:22 -0800852int
853PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 switch (opcode) {
856 case POP_TOP:
857 return -1;
858 case ROT_TWO:
859 case ROT_THREE:
860 return 0;
861 case DUP_TOP:
862 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000863 case DUP_TOP_TWO:
864 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 case UNARY_POSITIVE:
867 case UNARY_NEGATIVE:
868 case UNARY_NOT:
869 case UNARY_INVERT:
870 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case SET_ADD:
873 case LIST_APPEND:
874 return -1;
875 case MAP_ADD:
876 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case BINARY_POWER:
879 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400880 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case BINARY_MODULO:
882 case BINARY_ADD:
883 case BINARY_SUBTRACT:
884 case BINARY_SUBSCR:
885 case BINARY_FLOOR_DIVIDE:
886 case BINARY_TRUE_DIVIDE:
887 return -1;
888 case INPLACE_FLOOR_DIVIDE:
889 case INPLACE_TRUE_DIVIDE:
890 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case INPLACE_ADD:
893 case INPLACE_SUBTRACT:
894 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400895 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_MODULO:
897 return -1;
898 case STORE_SUBSCR:
899 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case DELETE_SUBSCR:
901 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_LSHIFT:
904 case BINARY_RSHIFT:
905 case BINARY_AND:
906 case BINARY_XOR:
907 case BINARY_OR:
908 return -1;
909 case INPLACE_POWER:
910 return -1;
911 case GET_ITER:
912 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case PRINT_EXPR:
915 return -1;
916 case LOAD_BUILD_CLASS:
917 return 1;
918 case INPLACE_LSHIFT:
919 case INPLACE_RSHIFT:
920 case INPLACE_AND:
921 case INPLACE_XOR:
922 case INPLACE_OR:
923 return -1;
924 case BREAK_LOOP:
925 return 0;
926 case SETUP_WITH:
927 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400928 case WITH_CLEANUP_START:
929 return 1;
930 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case RETURN_VALUE:
933 return -1;
934 case IMPORT_STAR:
935 return -1;
936 case YIELD_VALUE:
937 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500938 case YIELD_FROM:
939 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case POP_BLOCK:
941 return 0;
942 case POP_EXCEPT:
943 return 0; /* -3 except if bad bytecode */
944 case END_FINALLY:
945 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case STORE_NAME:
948 return -1;
949 case DELETE_NAME:
950 return 0;
951 case UNPACK_SEQUENCE:
952 return oparg-1;
953 case UNPACK_EX:
954 return (oparg&0xFF) + (oparg>>8);
955 case FOR_ITER:
956 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case STORE_ATTR:
959 return -2;
960 case DELETE_ATTR:
961 return -1;
962 case STORE_GLOBAL:
963 return -1;
964 case DELETE_GLOBAL:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case LOAD_CONST:
967 return 1;
968 case LOAD_NAME:
969 return 1;
970 case BUILD_TUPLE:
971 case BUILD_LIST:
972 case BUILD_SET:
973 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400974 case BUILD_LIST_UNPACK:
975 case BUILD_TUPLE_UNPACK:
976 case BUILD_SET_UNPACK:
977 case BUILD_MAP_UNPACK:
978 return 1 - oparg;
979 case BUILD_MAP_UNPACK_WITH_CALL:
980 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700982 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300983 case BUILD_CONST_KEY_MAP:
984 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 case LOAD_ATTR:
986 return 0;
987 case COMPARE_OP:
988 return -1;
989 case IMPORT_NAME:
990 return -1;
991 case IMPORT_FROM:
992 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 case JUMP_FORWARD:
995 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
996 case JUMP_IF_FALSE_OR_POP: /* "" */
997 case JUMP_ABSOLUTE:
998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case POP_JUMP_IF_FALSE:
1001 case POP_JUMP_IF_TRUE:
1002 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case LOAD_GLOBAL:
1005 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case CONTINUE_LOOP:
1008 return 0;
1009 case SETUP_LOOP:
1010 return 0;
1011 case SETUP_EXCEPT:
1012 case SETUP_FINALLY:
1013 return 6; /* can push 3 values for the new exception
1014 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case LOAD_FAST:
1017 return 1;
1018 case STORE_FAST:
1019 return -1;
1020 case DELETE_FAST:
1021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case RAISE_VARARGS:
1024 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001025#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 case CALL_FUNCTION:
1027 return -NARGS(oparg);
1028 case CALL_FUNCTION_VAR:
1029 case CALL_FUNCTION_KW:
1030 return -NARGS(oparg)-1;
1031 case CALL_FUNCTION_VAR_KW:
1032 return -NARGS(oparg)-2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001033#undef NARGS
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001034 case MAKE_FUNCTION:
1035 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1036 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case BUILD_SLICE:
1038 if (oparg == 3)
1039 return -2;
1040 else
1041 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_CLOSURE:
1044 return 1;
1045 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001046 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return 1;
1048 case STORE_DEREF:
1049 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001050 case DELETE_DEREF:
1051 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001052 case GET_AWAITABLE:
1053 return 0;
1054 case SETUP_ASYNC_WITH:
1055 return 6;
1056 case BEFORE_ASYNC_WITH:
1057 return 1;
1058 case GET_AITER:
1059 return 0;
1060 case GET_ANEXT:
1061 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001062 case GET_YIELD_FROM_ITER:
1063 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001064 case FORMAT_VALUE:
1065 /* If there's a fmt_spec on the stack, we go from 2->1,
1066 else 1->1. */
1067 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001069 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
Larry Hastings3a907972013-11-23 14:49:22 -08001071 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001072}
1073
1074/* Add an opcode with no argument.
1075 Returns 0 on failure, 1 on success.
1076*/
1077
1078static int
1079compiler_addop(struct compiler *c, int opcode)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 basicblock *b;
1082 struct instr *i;
1083 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001084 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 off = compiler_next_instr(c, c->u->u_curblock);
1086 if (off < 0)
1087 return 0;
1088 b = c->u->u_curblock;
1089 i = &b->b_instr[off];
1090 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001091 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (opcode == RETURN_VALUE)
1093 b->b_return = 1;
1094 compiler_set_lineno(c, off);
1095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096}
1097
Victor Stinnerf8e32212013-11-19 23:56:34 +01001098static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *t, *v;
1102 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Victor Stinnerefb24132016-01-22 12:33:12 +01001104 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (t == NULL)
1106 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 v = PyDict_GetItem(dict, t);
1109 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001110 if (PyErr_Occurred()) {
1111 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001115 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!v) {
1117 Py_DECREF(t);
1118 return -1;
1119 }
1120 if (PyDict_SetItem(dict, t, v) < 0) {
1121 Py_DECREF(t);
1122 Py_DECREF(v);
1123 return -1;
1124 }
1125 Py_DECREF(v);
1126 }
1127 else
1128 arg = PyLong_AsLong(v);
1129 Py_DECREF(t);
1130 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131}
1132
1133static int
1134compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001137 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return compiler_addop_i(c, opcode, arg);
1141}
1142
1143static int
1144compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1149 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001150 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 arg = compiler_add_o(c, dict, mangled);
1152 Py_DECREF(mangled);
1153 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return compiler_addop_i(c, opcode, arg);
1156}
1157
1158/* Add an opcode with an integer argument.
1159 Returns 0 on failure, 1 on success.
1160*/
1161
1162static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001163compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 struct instr *i;
1166 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001167
Victor Stinner2ad474b2016-03-01 23:34:47 +01001168 /* oparg value is unsigned, but a signed C int is usually used to store
1169 it in the C code (like Python/ceval.c).
1170
1171 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1172
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001173 The argument of a concrete bytecode instruction is limited to 8-bit.
1174 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1175 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001176 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 off = compiler_next_instr(c, c->u->u_curblock);
1179 if (off < 0)
1180 return 0;
1181 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001182 i->i_opcode = opcode;
1183 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 compiler_set_lineno(c, off);
1185 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188static int
1189compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct instr *i;
1192 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001194 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 assert(b != NULL);
1196 off = compiler_next_instr(c, c->u->u_curblock);
1197 if (off < 0)
1198 return 0;
1199 i = &c->u->u_curblock->b_instr[off];
1200 i->i_opcode = opcode;
1201 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (absolute)
1203 i->i_jabs = 1;
1204 else
1205 i->i_jrel = 1;
1206 compiler_set_lineno(c, off);
1207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208}
1209
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001210/* NEXT_BLOCK() creates an implicit jump from the current block
1211 to the new block.
1212
1213 The returns inside this macro make it impossible to decref objects
1214 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (compiler_next_block((C)) == NULL) \
1218 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219}
1220
1221#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (!compiler_addop((C), (OP))) \
1223 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224}
1225
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001226#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (!compiler_addop((C), (OP))) { \
1228 compiler_exit_scope(c); \
1229 return 0; \
1230 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001231}
1232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001238/* Same as ADDOP_O, but steals a reference. */
1239#define ADDOP_N(C, OP, O, TYPE) { \
1240 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1241 Py_DECREF((O)); \
1242 return 0; \
1243 } \
1244 Py_DECREF((O)); \
1245}
1246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1249 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (!compiler_addop_i((C), (OP), (O))) \
1254 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_j((C), (OP), (O), 1)) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_j((C), (OP), (O), 0)) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1268 the ASDL name to synthesize the name of the C type and the visit function.
1269*/
1270
1271#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!compiler_visit_ ## TYPE((C), (V))) \
1273 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001276#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_visit_ ## TYPE((C), (V))) { \
1278 compiler_exit_scope(c); \
1279 return 0; \
1280 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001281}
1282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_visit_slice((C), (V), (CTX))) \
1285 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286}
1287
1288#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 int _i; \
1290 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1291 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1292 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1293 if (!compiler_visit_ ## TYPE((C), elt)) \
1294 return 0; \
1295 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001298#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 int _i; \
1300 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1301 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1302 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1303 if (!compiler_visit_ ## TYPE((C), elt)) { \
1304 compiler_exit_scope(c); \
1305 return 0; \
1306 } \
1307 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308}
1309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310static int
1311compiler_isdocstring(stmt_ty s)
1312{
1313 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001314 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001315 if (s->v.Expr.value->kind == Str_kind)
1316 return 1;
1317 if (s->v.Expr.value->kind == Constant_kind)
1318 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1319 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001322static int
1323is_const(expr_ty e)
1324{
1325 switch (e->kind) {
1326 case Constant_kind:
1327 case Num_kind:
1328 case Str_kind:
1329 case Bytes_kind:
1330 case Ellipsis_kind:
1331 case NameConstant_kind:
1332 return 1;
1333 default:
1334 return 0;
1335 }
1336}
1337
1338static PyObject *
1339get_const_value(expr_ty e)
1340{
1341 switch (e->kind) {
1342 case Constant_kind:
1343 return e->v.Constant.value;
1344 case Num_kind:
1345 return e->v.Num.n;
1346 case Str_kind:
1347 return e->v.Str.s;
1348 case Bytes_kind:
1349 return e->v.Bytes.s;
1350 case Ellipsis_kind:
1351 return Py_Ellipsis;
1352 case NameConstant_kind:
1353 return e->v.NameConstant.value;
1354 default:
1355 assert(!is_const(e));
1356 return NULL;
1357 }
1358}
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360/* Compile a sequence of statements, checking for a docstring. */
1361
1362static int
1363compiler_body(struct compiler *c, asdl_seq *stmts)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 int i = 0;
1366 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!asdl_seq_LEN(stmts))
1369 return 1;
1370 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001371 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* don't generate docstrings if -OO */
1373 i = 1;
1374 VISIT(c, expr, st->v.Expr.value);
1375 if (!compiler_nameop(c, __doc__, Store))
1376 return 0;
1377 }
1378 for (; i < asdl_seq_LEN(stmts); i++)
1379 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1380 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381}
1382
1383static PyCodeObject *
1384compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyCodeObject *co;
1387 int addNone = 1;
1388 static PyObject *module;
1389 if (!module) {
1390 module = PyUnicode_InternFromString("<module>");
1391 if (!module)
1392 return NULL;
1393 }
1394 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001395 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 return NULL;
1397 switch (mod->kind) {
1398 case Module_kind:
1399 if (!compiler_body(c, mod->v.Module.body)) {
1400 compiler_exit_scope(c);
1401 return 0;
1402 }
1403 break;
1404 case Interactive_kind:
1405 c->c_interactive = 1;
1406 VISIT_SEQ_IN_SCOPE(c, stmt,
1407 mod->v.Interactive.body);
1408 break;
1409 case Expression_kind:
1410 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1411 addNone = 0;
1412 break;
1413 case Suite_kind:
1414 PyErr_SetString(PyExc_SystemError,
1415 "suite should not be possible");
1416 return 0;
1417 default:
1418 PyErr_Format(PyExc_SystemError,
1419 "module kind %d should not be possible",
1420 mod->kind);
1421 return 0;
1422 }
1423 co = assemble(c, addNone);
1424 compiler_exit_scope(c);
1425 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001426}
1427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428/* The test for LOCAL must come before the test for FREE in order to
1429 handle classes where name is both local and free. The local var is
1430 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001431*/
1432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433static int
1434get_ref_type(struct compiler *c, PyObject *name)
1435{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001436 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001437 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1438 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1439 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001440 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (scope == 0) {
1442 char buf[350];
1443 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001444 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001446 PyUnicode_AsUTF8(name),
1447 PyUnicode_AsUTF8(c->u->u_name),
1448 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1449 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1450 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1451 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 );
1453 Py_FatalError(buf);
1454 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457}
1458
1459static int
1460compiler_lookup_arg(PyObject *dict, PyObject *name)
1461{
1462 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001463 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001465 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001467 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001469 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001470 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
1473static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001474compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001476 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001477 if (qualname == NULL)
1478 qualname = co->co_name;
1479
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001480 if (free) {
1481 for (i = 0; i < free; ++i) {
1482 /* Bypass com_addop_varname because it will generate
1483 LOAD_DEREF but LOAD_CLOSURE is needed.
1484 */
1485 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1486 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001488 /* Special case: If a class contains a method with a
1489 free variable that has the same name as a method,
1490 the name will be considered free *and* local in the
1491 class. It should be handled by the closure, as
1492 well as by the normal name loookup logic.
1493 */
1494 reftype = get_ref_type(c, name);
1495 if (reftype == CELL)
1496 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1497 else /* (reftype == FREE) */
1498 arg = compiler_lookup_arg(c->u->u_freevars, name);
1499 if (arg == -1) {
1500 fprintf(stderr,
1501 "lookup %s in %s %d %d\n"
1502 "freevars of %s: %s\n",
1503 PyUnicode_AsUTF8(PyObject_Repr(name)),
1504 PyUnicode_AsUTF8(c->u->u_name),
1505 reftype, arg,
1506 PyUnicode_AsUTF8(co->co_name),
1507 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1508 Py_FatalError("compiler_make_closure()");
1509 }
1510 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001512 flags |= 0x08;
1513 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001516 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001517 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
1521static int
1522compiler_decorators(struct compiler *c, asdl_seq* decos)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!decos)
1527 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1530 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1531 }
1532 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
1535static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001536compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001538{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001539 /* Push a dict of keyword-only default values.
1540
1541 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1542 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001543 int i;
1544 PyObject *keys = NULL;
1545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1547 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1548 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1549 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001550 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001551 if (!mangled) {
1552 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001554 if (keys == NULL) {
1555 keys = PyList_New(1);
1556 if (keys == NULL) {
1557 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001558 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001559 }
1560 PyList_SET_ITEM(keys, 0, mangled);
1561 }
1562 else {
1563 int res = PyList_Append(keys, mangled);
1564 Py_DECREF(mangled);
1565 if (res == -1) {
1566 goto error;
1567 }
1568 }
1569 if (!compiler_visit_expr(c, default_)) {
1570 goto error;
1571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 }
1573 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001574 if (keys != NULL) {
1575 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1576 PyObject *keys_tuple = PyList_AsTuple(keys);
1577 Py_DECREF(keys);
1578 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001579 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001580 }
1581 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1582 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001583 assert(default_count > 0);
1584 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001585 }
1586 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001587 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001588 }
1589
1590error:
1591 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001592 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001593}
1594
1595static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001596compiler_visit_argannotation(struct compiler *c, identifier id,
1597 expr_ty annotation, PyObject *names)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001600 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001602 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001603 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001604 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001605 if (PyList_Append(names, mangled) < 0) {
1606 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001607 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001608 }
1609 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001611 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001612}
1613
1614static int
1615compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1616 PyObject *names)
1617{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001618 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 for (i = 0; i < asdl_seq_LEN(args); i++) {
1620 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001621 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 c,
1623 arg->arg,
1624 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001625 names))
1626 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001628 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001629}
1630
1631static int
1632compiler_visit_annotations(struct compiler *c, arguments_ty args,
1633 expr_ty returns)
1634{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001635 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001636 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001637
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001638 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 */
1640 static identifier return_str;
1641 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001642 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 names = PyList_New(0);
1644 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001645 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001646
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001647 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001649 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001650 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001651 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001653 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001655 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001656 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001657 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (!return_str) {
1661 return_str = PyUnicode_InternFromString("return");
1662 if (!return_str)
1663 goto error;
1664 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001665 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 goto error;
1667 }
1668
1669 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001671 PyObject *keytuple = PyList_AsTuple(names);
1672 Py_DECREF(names);
1673 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001674 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001676 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1677 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001678 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001680 else {
1681 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001682 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001683 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001684
1685error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001687 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001688}
1689
1690static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001691compiler_visit_defaults(struct compiler *c, arguments_ty args)
1692{
1693 VISIT_SEQ(c, expr, args->defaults);
1694 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1695 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696}
1697
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001698static Py_ssize_t
1699compiler_default_arguments(struct compiler *c, arguments_ty args)
1700{
1701 Py_ssize_t funcflags = 0;
1702 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001703 if (!compiler_visit_defaults(c, args))
1704 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001705 funcflags |= 0x01;
1706 }
1707 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001708 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001709 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001710 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001711 return -1;
1712 }
1713 else if (res > 0) {
1714 funcflags |= 0x02;
1715 }
1716 }
1717 return funcflags;
1718}
1719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720static int
Yury Selivanov75445082015-05-11 22:57:16 -04001721compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001724 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001725 arguments_ty args;
1726 expr_ty returns;
1727 identifier name;
1728 asdl_seq* decos;
1729 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001731 Py_ssize_t i, n, funcflags;
1732 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001733 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001734 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735
Yury Selivanov75445082015-05-11 22:57:16 -04001736 if (is_async) {
1737 assert(s->kind == AsyncFunctionDef_kind);
1738
1739 args = s->v.AsyncFunctionDef.args;
1740 returns = s->v.AsyncFunctionDef.returns;
1741 decos = s->v.AsyncFunctionDef.decorator_list;
1742 name = s->v.AsyncFunctionDef.name;
1743 body = s->v.AsyncFunctionDef.body;
1744
1745 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1746 } else {
1747 assert(s->kind == FunctionDef_kind);
1748
1749 args = s->v.FunctionDef.args;
1750 returns = s->v.FunctionDef.returns;
1751 decos = s->v.FunctionDef.decorator_list;
1752 name = s->v.FunctionDef.name;
1753 body = s->v.FunctionDef.body;
1754
1755 scope_type = COMPILER_SCOPE_FUNCTION;
1756 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (!compiler_decorators(c, decos))
1759 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001760
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761 funcflags = compiler_default_arguments(c, args);
1762 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001764 }
1765
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001766 annotations = compiler_visit_annotations(c, args, returns);
1767 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 return 0;
1769 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001770 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001771 funcflags |= 0x04;
1772 }
1773
1774 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1775 return 0;
1776 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777
Yury Selivanov75445082015-05-11 22:57:16 -04001778 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001780 if (docstring && c->c_optimize < 2) {
1781 if (st->v.Expr.value->kind == Constant_kind)
1782 first_const = st->v.Expr.value->v.Constant.value;
1783 else
1784 first_const = st->v.Expr.value->v.Str.s;
1785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1787 compiler_exit_scope(c);
1788 return 0;
1789 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 c->u->u_argcount = asdl_seq_LEN(args->args);
1792 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001793 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* if there was a docstring, we need to skip the first statement */
1795 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001796 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 VISIT_IN_SCOPE(c, stmt, st);
1798 }
1799 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001800 qualname = c->u->u_qualname;
1801 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001803 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001804 Py_XDECREF(qualname);
1805 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001807 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808
Yury Selivanovb7666a32015-07-22 14:48:57 +03001809 if (is_async)
1810 co->co_flags |= CO_COROUTINE;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001812 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 /* decorators */
1816 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1817 ADDOP_I(c, CALL_FUNCTION, 1);
1818 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819
Yury Selivanov75445082015-05-11 22:57:16 -04001820 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821}
1822
1823static int
1824compiler_class(struct compiler *c, stmt_ty s)
1825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyCodeObject *co;
1827 PyObject *str;
1828 int i;
1829 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (!compiler_decorators(c, decos))
1832 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* ultimately generate code for:
1835 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1836 where:
1837 <func> is a function/closure created from the class body;
1838 it has a single argument (__locals__) where the dict
1839 (or MutableSequence) representing the locals is passed
1840 <name> is the class name
1841 <bases> is the positional arguments and *varargs argument
1842 <keywords> is the keyword arguments and **kwds argument
1843 This borrows from compiler_call.
1844 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001847 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1848 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return 0;
1850 /* this block represents what we do in the new scope */
1851 {
1852 /* use the class name for name mangling */
1853 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001854 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 /* load (global) __name__ ... */
1856 str = PyUnicode_InternFromString("__name__");
1857 if (!str || !compiler_nameop(c, str, Load)) {
1858 Py_XDECREF(str);
1859 compiler_exit_scope(c);
1860 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001861 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 Py_DECREF(str);
1863 /* ... and store it as __module__ */
1864 str = PyUnicode_InternFromString("__module__");
1865 if (!str || !compiler_nameop(c, str, Store)) {
1866 Py_XDECREF(str);
1867 compiler_exit_scope(c);
1868 return 0;
1869 }
1870 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001871 assert(c->u->u_qualname);
1872 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001873 str = PyUnicode_InternFromString("__qualname__");
1874 if (!str || !compiler_nameop(c, str, Store)) {
1875 Py_XDECREF(str);
1876 compiler_exit_scope(c);
1877 return 0;
1878 }
1879 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 /* compile the body proper */
1881 if (!compiler_body(c, s->v.ClassDef.body)) {
1882 compiler_exit_scope(c);
1883 return 0;
1884 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001885 if (c->u->u_ste->ste_needs_class_closure) {
1886 /* return the (empty) __class__ cell */
1887 str = PyUnicode_InternFromString("__class__");
1888 if (str == NULL) {
1889 compiler_exit_scope(c);
1890 return 0;
1891 }
1892 i = compiler_lookup_arg(c->u->u_cellvars, str);
1893 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001894 if (i < 0) {
1895 compiler_exit_scope(c);
1896 return 0;
1897 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001898 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Return the cell where to store __class__ */
1900 ADDOP_I(c, LOAD_CLOSURE, i);
1901 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001902 else {
1903 assert(PyDict_Size(c->u->u_cellvars) == 0);
1904 /* This happens when nobody references the cell. Return None. */
1905 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1906 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1908 /* create the code object */
1909 co = assemble(c, 1);
1910 }
1911 /* leave the new scope */
1912 compiler_exit_scope(c);
1913 if (co == NULL)
1914 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 /* 2. load the 'build_class' function */
1917 ADDOP(c, LOAD_BUILD_CLASS);
1918
1919 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001920 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_DECREF(co);
1922
1923 /* 4. load class name */
1924 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1925
1926 /* 5. generate the rest of the code for the call */
1927 if (!compiler_call_helper(c, 2,
1928 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001929 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 return 0;
1931
1932 /* 6. apply decorators */
1933 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1934 ADDOP_I(c, CALL_FUNCTION, 1);
1935 }
1936
1937 /* 7. store into <name> */
1938 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1939 return 0;
1940 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941}
1942
1943static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001944compiler_ifexp(struct compiler *c, expr_ty e)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 basicblock *end, *next;
1947
1948 assert(e->kind == IfExp_kind);
1949 end = compiler_new_block(c);
1950 if (end == NULL)
1951 return 0;
1952 next = compiler_new_block(c);
1953 if (next == NULL)
1954 return 0;
1955 VISIT(c, expr, e->v.IfExp.test);
1956 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1957 VISIT(c, expr, e->v.IfExp.body);
1958 ADDOP_JREL(c, JUMP_FORWARD, end);
1959 compiler_use_next_block(c, next);
1960 VISIT(c, expr, e->v.IfExp.orelse);
1961 compiler_use_next_block(c, end);
1962 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001963}
1964
1965static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966compiler_lambda(struct compiler *c, expr_ty e)
1967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001969 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001971 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 arguments_ty args = e->v.Lambda.args;
1973 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (!name) {
1976 name = PyUnicode_InternFromString("<lambda>");
1977 if (!name)
1978 return 0;
1979 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001981 funcflags = compiler_default_arguments(c, args);
1982 if (funcflags == -1) {
1983 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001986 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001987 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 /* Make None the first constant, so the lambda can't have a
1991 docstring. */
1992 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1993 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 c->u->u_argcount = asdl_seq_LEN(args->args);
1996 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1997 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1998 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001999 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
2001 else {
2002 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002003 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002005 qualname = c->u->u_qualname;
2006 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002008 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002012 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 Py_DECREF(co);
2014
2015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016}
2017
2018static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019compiler_if(struct compiler *c, stmt_ty s)
2020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 basicblock *end, *next;
2022 int constant;
2023 assert(s->kind == If_kind);
2024 end = compiler_new_block(c);
2025 if (end == NULL)
2026 return 0;
2027
Georg Brandl8334fd92010-12-04 10:26:46 +00002028 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* constant = 0: "if 0"
2030 * constant = 1: "if 1", "if 2", ...
2031 * constant = -1: rest */
2032 if (constant == 0) {
2033 if (s->v.If.orelse)
2034 VISIT_SEQ(c, stmt, s->v.If.orelse);
2035 } else if (constant == 1) {
2036 VISIT_SEQ(c, stmt, s->v.If.body);
2037 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002038 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 next = compiler_new_block(c);
2040 if (next == NULL)
2041 return 0;
2042 }
2043 else
2044 next = end;
2045 VISIT(c, expr, s->v.If.test);
2046 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2047 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002048 if (asdl_seq_LEN(s->v.If.orelse)) {
2049 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 compiler_use_next_block(c, next);
2051 VISIT_SEQ(c, stmt, s->v.If.orelse);
2052 }
2053 }
2054 compiler_use_next_block(c, end);
2055 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056}
2057
2058static int
2059compiler_for(struct compiler *c, stmt_ty s)
2060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 start = compiler_new_block(c);
2064 cleanup = compiler_new_block(c);
2065 end = compiler_new_block(c);
2066 if (start == NULL || end == NULL || cleanup == NULL)
2067 return 0;
2068 ADDOP_JREL(c, SETUP_LOOP, end);
2069 if (!compiler_push_fblock(c, LOOP, start))
2070 return 0;
2071 VISIT(c, expr, s->v.For.iter);
2072 ADDOP(c, GET_ITER);
2073 compiler_use_next_block(c, start);
2074 ADDOP_JREL(c, FOR_ITER, cleanup);
2075 VISIT(c, expr, s->v.For.target);
2076 VISIT_SEQ(c, stmt, s->v.For.body);
2077 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2078 compiler_use_next_block(c, cleanup);
2079 ADDOP(c, POP_BLOCK);
2080 compiler_pop_fblock(c, LOOP, start);
2081 VISIT_SEQ(c, stmt, s->v.For.orelse);
2082 compiler_use_next_block(c, end);
2083 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084}
2085
Yury Selivanov75445082015-05-11 22:57:16 -04002086
2087static int
2088compiler_async_for(struct compiler *c, stmt_ty s)
2089{
2090 static PyObject *stopiter_error = NULL;
2091 basicblock *try, *except, *end, *after_try, *try_cleanup,
2092 *after_loop, *after_loop_else;
2093
2094 if (stopiter_error == NULL) {
2095 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2096 if (stopiter_error == NULL)
2097 return 0;
2098 }
2099
2100 try = compiler_new_block(c);
2101 except = compiler_new_block(c);
2102 end = compiler_new_block(c);
2103 after_try = compiler_new_block(c);
2104 try_cleanup = compiler_new_block(c);
2105 after_loop = compiler_new_block(c);
2106 after_loop_else = compiler_new_block(c);
2107
2108 if (try == NULL || except == NULL || end == NULL
2109 || after_try == NULL || try_cleanup == NULL)
2110 return 0;
2111
2112 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2113 if (!compiler_push_fblock(c, LOOP, try))
2114 return 0;
2115
2116 VISIT(c, expr, s->v.AsyncFor.iter);
2117 ADDOP(c, GET_AITER);
2118 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2119 ADDOP(c, YIELD_FROM);
2120
2121 compiler_use_next_block(c, try);
2122
2123
2124 ADDOP_JREL(c, SETUP_EXCEPT, except);
2125 if (!compiler_push_fblock(c, EXCEPT, try))
2126 return 0;
2127
2128 ADDOP(c, GET_ANEXT);
2129 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2130 ADDOP(c, YIELD_FROM);
2131 VISIT(c, expr, s->v.AsyncFor.target);
2132 ADDOP(c, POP_BLOCK);
2133 compiler_pop_fblock(c, EXCEPT, try);
2134 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2135
2136
2137 compiler_use_next_block(c, except);
2138 ADDOP(c, DUP_TOP);
2139 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2140 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2141 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2142
2143 ADDOP(c, POP_TOP);
2144 ADDOP(c, POP_TOP);
2145 ADDOP(c, POP_TOP);
2146 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2147 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2148 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2149
2150
2151 compiler_use_next_block(c, try_cleanup);
2152 ADDOP(c, END_FINALLY);
2153
2154 compiler_use_next_block(c, after_try);
2155 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2156 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2157
2158 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2159 compiler_pop_fblock(c, LOOP, try);
2160
2161 compiler_use_next_block(c, after_loop);
2162 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2163
2164 compiler_use_next_block(c, after_loop_else);
2165 VISIT_SEQ(c, stmt, s->v.For.orelse);
2166
2167 compiler_use_next_block(c, end);
2168
2169 return 1;
2170}
2171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172static int
2173compiler_while(struct compiler *c, stmt_ty s)
2174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002176 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (constant == 0) {
2179 if (s->v.While.orelse)
2180 VISIT_SEQ(c, stmt, s->v.While.orelse);
2181 return 1;
2182 }
2183 loop = compiler_new_block(c);
2184 end = compiler_new_block(c);
2185 if (constant == -1) {
2186 anchor = compiler_new_block(c);
2187 if (anchor == NULL)
2188 return 0;
2189 }
2190 if (loop == NULL || end == NULL)
2191 return 0;
2192 if (s->v.While.orelse) {
2193 orelse = compiler_new_block(c);
2194 if (orelse == NULL)
2195 return 0;
2196 }
2197 else
2198 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 ADDOP_JREL(c, SETUP_LOOP, end);
2201 compiler_use_next_block(c, loop);
2202 if (!compiler_push_fblock(c, LOOP, loop))
2203 return 0;
2204 if (constant == -1) {
2205 VISIT(c, expr, s->v.While.test);
2206 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2207 }
2208 VISIT_SEQ(c, stmt, s->v.While.body);
2209 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* XXX should the two POP instructions be in a separate block
2212 if there is no else clause ?
2213 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002215 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002217 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 compiler_pop_fblock(c, LOOP, loop);
2219 if (orelse != NULL) /* what if orelse is just pass? */
2220 VISIT_SEQ(c, stmt, s->v.While.orelse);
2221 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224}
2225
2226static int
2227compiler_continue(struct compiler *c)
2228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2230 static const char IN_FINALLY_ERROR_MSG[] =
2231 "'continue' not supported inside 'finally' clause";
2232 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (!c->u->u_nfblocks)
2235 return compiler_error(c, LOOP_ERROR_MSG);
2236 i = c->u->u_nfblocks - 1;
2237 switch (c->u->u_fblock[i].fb_type) {
2238 case LOOP:
2239 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2240 break;
2241 case EXCEPT:
2242 case FINALLY_TRY:
2243 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2244 /* Prevent continue anywhere under a finally
2245 even if hidden in a sub-try or except. */
2246 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2247 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2248 }
2249 if (i == -1)
2250 return compiler_error(c, LOOP_ERROR_MSG);
2251 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2252 break;
2253 case FINALLY_END:
2254 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258}
2259
2260/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261
2262 SETUP_FINALLY L
2263 <code for body>
2264 POP_BLOCK
2265 LOAD_CONST <None>
2266 L: <code for finalbody>
2267 END_FINALLY
2268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 The special instructions use the block stack. Each block
2270 stack entry contains the instruction that created it (here
2271 SETUP_FINALLY), the level of the value stack at the time the
2272 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 Pushes the current value stack level and the label
2276 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 Pops en entry from the block stack, and pops the value
2279 stack until its level is the same as indicated on the
2280 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 Pops a variable number of entries from the *value* stack
2283 and re-raises the exception they specify. The number of
2284 entries popped depends on the (pseudo) exception type.
2285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286 The block stack is unwound when an exception is raised:
2287 when a SETUP_FINALLY entry is found, the exception is pushed
2288 onto the value stack (and the exception condition is cleared),
2289 and the interpreter jumps to the label gotten from the block
2290 stack.
2291*/
2292
2293static int
2294compiler_try_finally(struct compiler *c, stmt_ty s)
2295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 basicblock *body, *end;
2297 body = compiler_new_block(c);
2298 end = compiler_new_block(c);
2299 if (body == NULL || end == NULL)
2300 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 ADDOP_JREL(c, SETUP_FINALLY, end);
2303 compiler_use_next_block(c, body);
2304 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2305 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002306 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2307 if (!compiler_try_except(c, s))
2308 return 0;
2309 }
2310 else {
2311 VISIT_SEQ(c, stmt, s->v.Try.body);
2312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 ADDOP(c, POP_BLOCK);
2314 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2317 compiler_use_next_block(c, end);
2318 if (!compiler_push_fblock(c, FINALLY_END, end))
2319 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002320 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 ADDOP(c, END_FINALLY);
2322 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325}
2326
2327/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002328 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 (The contents of the value stack is shown in [], with the top
2330 at the right; 'tb' is trace-back info, 'val' the exception's
2331 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332
2333 Value stack Label Instruction Argument
2334 [] SETUP_EXCEPT L1
2335 [] <code for S>
2336 [] POP_BLOCK
2337 [] JUMP_FORWARD L0
2338
2339 [tb, val, exc] L1: DUP )
2340 [tb, val, exc, exc] <evaluate E1> )
2341 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2342 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2343 [tb, val, exc] POP
2344 [tb, val] <assign to V1> (or POP if no V1)
2345 [tb] POP
2346 [] <code for S1>
2347 JUMP_FORWARD L0
2348
2349 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350 .............................etc.......................
2351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2353
2354 [] L0: <next statement>
2355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 Of course, parts are not generated if Vi or Ei is not present.
2357*/
2358static int
2359compiler_try_except(struct compiler *c, stmt_ty s)
2360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002362 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 body = compiler_new_block(c);
2365 except = compiler_new_block(c);
2366 orelse = compiler_new_block(c);
2367 end = compiler_new_block(c);
2368 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2369 return 0;
2370 ADDOP_JREL(c, SETUP_EXCEPT, except);
2371 compiler_use_next_block(c, body);
2372 if (!compiler_push_fblock(c, EXCEPT, body))
2373 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002374 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 ADDOP(c, POP_BLOCK);
2376 compiler_pop_fblock(c, EXCEPT, body);
2377 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002378 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 compiler_use_next_block(c, except);
2380 for (i = 0; i < n; i++) {
2381 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002382 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (!handler->v.ExceptHandler.type && i < n-1)
2384 return compiler_error(c, "default 'except:' must be last");
2385 c->u->u_lineno_set = 0;
2386 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002387 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 except = compiler_new_block(c);
2389 if (except == NULL)
2390 return 0;
2391 if (handler->v.ExceptHandler.type) {
2392 ADDOP(c, DUP_TOP);
2393 VISIT(c, expr, handler->v.ExceptHandler.type);
2394 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2395 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2396 }
2397 ADDOP(c, POP_TOP);
2398 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002399 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002400
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002401 cleanup_end = compiler_new_block(c);
2402 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002403 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002404 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002405
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002406 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2407 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002409 /*
2410 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002411 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002412 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002413 try:
2414 # body
2415 finally:
2416 name = None
2417 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002418 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002420 /* second try: */
2421 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2422 compiler_use_next_block(c, cleanup_body);
2423 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2424 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002426 /* second # body */
2427 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2428 ADDOP(c, POP_BLOCK);
2429 ADDOP(c, POP_EXCEPT);
2430 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002432 /* finally: */
2433 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2434 compiler_use_next_block(c, cleanup_end);
2435 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2436 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002438 /* name = None */
2439 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2440 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002442 /* del name */
2443 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002445 ADDOP(c, END_FINALLY);
2446 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 }
2448 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002449 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002451 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002452 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002453 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454
Guido van Rossumb940e112007-01-10 16:19:56 +00002455 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002456 ADDOP(c, POP_TOP);
2457 compiler_use_next_block(c, cleanup_body);
2458 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2459 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002461 ADDOP(c, POP_EXCEPT);
2462 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 }
2464 ADDOP_JREL(c, JUMP_FORWARD, end);
2465 compiler_use_next_block(c, except);
2466 }
2467 ADDOP(c, END_FINALLY);
2468 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002469 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 compiler_use_next_block(c, end);
2471 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472}
2473
2474static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002475compiler_try(struct compiler *c, stmt_ty s) {
2476 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2477 return compiler_try_finally(c, s);
2478 else
2479 return compiler_try_except(c, s);
2480}
2481
2482
2483static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484compiler_import_as(struct compiler *c, identifier name, identifier asname)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* The IMPORT_NAME opcode was already generated. This function
2487 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 If there is a dot in name, we need to split it and emit a
2490 LOAD_ATTR for each name.
2491 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2493 PyUnicode_GET_LENGTH(name), 1);
2494 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002495 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 Py_ssize_t pos = dot + 1;
2499 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 dot = PyUnicode_FindChar(name, '.', pos,
2502 PyUnicode_GET_LENGTH(name), 1);
2503 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002504 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 attr = PyUnicode_Substring(name, pos,
2506 (dot != -1) ? dot :
2507 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002509 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 ADDOP_O(c, LOAD_ATTR, attr, names);
2511 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 }
2514 }
2515 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516}
2517
2518static int
2519compiler_import(struct compiler *c, stmt_ty s)
2520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* The Import node stores a module name like a.b.c as a single
2522 string. This is convenient for all cases except
2523 import a.b.c as d
2524 where we need to parse that string to extract the individual
2525 module names.
2526 XXX Perhaps change the representation to make this case simpler?
2527 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002528 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 for (i = 0; i < n; i++) {
2531 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2532 int r;
2533 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 level = PyLong_FromLong(0);
2536 if (level == NULL)
2537 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 ADDOP_O(c, LOAD_CONST, level, consts);
2540 Py_DECREF(level);
2541 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2542 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 if (alias->asname) {
2545 r = compiler_import_as(c, alias->name, alias->asname);
2546 if (!r)
2547 return r;
2548 }
2549 else {
2550 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 Py_ssize_t dot = PyUnicode_FindChar(
2552 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002553 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002554 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002555 if (tmp == NULL)
2556 return 0;
2557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 Py_DECREF(tmp);
2561 }
2562 if (!r)
2563 return r;
2564 }
2565 }
2566 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567}
2568
2569static int
2570compiler_from_import(struct compiler *c, stmt_ty s)
2571{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002572 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 PyObject *names = PyTuple_New(n);
2575 PyObject *level;
2576 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (!empty_string) {
2579 empty_string = PyUnicode_FromString("");
2580 if (!empty_string)
2581 return 0;
2582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 if (!names)
2585 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 level = PyLong_FromLong(s->v.ImportFrom.level);
2588 if (!level) {
2589 Py_DECREF(names);
2590 return 0;
2591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 /* build up the names */
2594 for (i = 0; i < n; i++) {
2595 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2596 Py_INCREF(alias->name);
2597 PyTuple_SET_ITEM(names, i, alias->name);
2598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2601 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2602 Py_DECREF(level);
2603 Py_DECREF(names);
2604 return compiler_error(c, "from __future__ imports must occur "
2605 "at the beginning of the file");
2606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 ADDOP_O(c, LOAD_CONST, level, consts);
2609 Py_DECREF(level);
2610 ADDOP_O(c, LOAD_CONST, names, consts);
2611 Py_DECREF(names);
2612 if (s->v.ImportFrom.module) {
2613 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2614 }
2615 else {
2616 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2617 }
2618 for (i = 0; i < n; i++) {
2619 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2620 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 assert(n == 1);
2624 ADDOP(c, IMPORT_STAR);
2625 return 1;
2626 }
2627
2628 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2629 store_name = alias->name;
2630 if (alias->asname)
2631 store_name = alias->asname;
2632
2633 if (!compiler_nameop(c, store_name, Store)) {
2634 Py_DECREF(names);
2635 return 0;
2636 }
2637 }
2638 /* remove imported module */
2639 ADDOP(c, POP_TOP);
2640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641}
2642
2643static int
2644compiler_assert(struct compiler *c, stmt_ty s)
2645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 static PyObject *assertion_error = NULL;
2647 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002648 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649
Georg Brandl8334fd92010-12-04 10:26:46 +00002650 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return 1;
2652 if (assertion_error == NULL) {
2653 assertion_error = PyUnicode_InternFromString("AssertionError");
2654 if (assertion_error == NULL)
2655 return 0;
2656 }
2657 if (s->v.Assert.test->kind == Tuple_kind &&
2658 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002659 msg = PyUnicode_FromString("assertion is always true, "
2660 "perhaps remove parentheses?");
2661 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002663 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2664 c->c_filename, c->u->u_lineno,
2665 NULL, NULL) == -1) {
2666 Py_DECREF(msg);
2667 return 0;
2668 }
2669 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 }
2671 VISIT(c, expr, s->v.Assert.test);
2672 end = compiler_new_block(c);
2673 if (end == NULL)
2674 return 0;
2675 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2676 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2677 if (s->v.Assert.msg) {
2678 VISIT(c, expr, s->v.Assert.msg);
2679 ADDOP_I(c, CALL_FUNCTION, 1);
2680 }
2681 ADDOP_I(c, RAISE_VARARGS, 1);
2682 compiler_use_next_block(c, end);
2683 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684}
2685
2686static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002687compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2688{
2689 if (c->c_interactive && c->c_nestlevel <= 1) {
2690 VISIT(c, expr, value);
2691 ADDOP(c, PRINT_EXPR);
2692 return 1;
2693 }
2694
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002695 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002696 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002697 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002698 }
2699
2700 VISIT(c, expr, value);
2701 ADDOP(c, POP_TOP);
2702 return 1;
2703}
2704
2705static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706compiler_visit_stmt(struct compiler *c, stmt_ty s)
2707{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002708 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 /* Always assign a lineno to the next instruction for a stmt. */
2711 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002712 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 switch (s->kind) {
2716 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002717 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 case ClassDef_kind:
2719 return compiler_class(c, s);
2720 case Return_kind:
2721 if (c->u->u_ste->ste_type != FunctionBlock)
2722 return compiler_error(c, "'return' outside function");
2723 if (s->v.Return.value) {
2724 VISIT(c, expr, s->v.Return.value);
2725 }
2726 else
2727 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2728 ADDOP(c, RETURN_VALUE);
2729 break;
2730 case Delete_kind:
2731 VISIT_SEQ(c, expr, s->v.Delete.targets)
2732 break;
2733 case Assign_kind:
2734 n = asdl_seq_LEN(s->v.Assign.targets);
2735 VISIT(c, expr, s->v.Assign.value);
2736 for (i = 0; i < n; i++) {
2737 if (i < n - 1)
2738 ADDOP(c, DUP_TOP);
2739 VISIT(c, expr,
2740 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2741 }
2742 break;
2743 case AugAssign_kind:
2744 return compiler_augassign(c, s);
2745 case For_kind:
2746 return compiler_for(c, s);
2747 case While_kind:
2748 return compiler_while(c, s);
2749 case If_kind:
2750 return compiler_if(c, s);
2751 case Raise_kind:
2752 n = 0;
2753 if (s->v.Raise.exc) {
2754 VISIT(c, expr, s->v.Raise.exc);
2755 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002756 if (s->v.Raise.cause) {
2757 VISIT(c, expr, s->v.Raise.cause);
2758 n++;
2759 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002761 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002763 case Try_kind:
2764 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 case Assert_kind:
2766 return compiler_assert(c, s);
2767 case Import_kind:
2768 return compiler_import(c, s);
2769 case ImportFrom_kind:
2770 return compiler_from_import(c, s);
2771 case Global_kind:
2772 case Nonlocal_kind:
2773 break;
2774 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002775 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 case Pass_kind:
2777 break;
2778 case Break_kind:
2779 if (!compiler_in_loop(c))
2780 return compiler_error(c, "'break' outside loop");
2781 ADDOP(c, BREAK_LOOP);
2782 break;
2783 case Continue_kind:
2784 return compiler_continue(c);
2785 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002786 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002787 case AsyncFunctionDef_kind:
2788 return compiler_function(c, s, 1);
2789 case AsyncWith_kind:
2790 return compiler_async_with(c, s, 0);
2791 case AsyncFor_kind:
2792 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 }
Yury Selivanov75445082015-05-11 22:57:16 -04002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796}
2797
2798static int
2799unaryop(unaryop_ty op)
2800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 switch (op) {
2802 case Invert:
2803 return UNARY_INVERT;
2804 case Not:
2805 return UNARY_NOT;
2806 case UAdd:
2807 return UNARY_POSITIVE;
2808 case USub:
2809 return UNARY_NEGATIVE;
2810 default:
2811 PyErr_Format(PyExc_SystemError,
2812 "unary op %d should not be possible", op);
2813 return 0;
2814 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815}
2816
2817static int
2818binop(struct compiler *c, operator_ty op)
2819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 switch (op) {
2821 case Add:
2822 return BINARY_ADD;
2823 case Sub:
2824 return BINARY_SUBTRACT;
2825 case Mult:
2826 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002827 case MatMult:
2828 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 case Div:
2830 return BINARY_TRUE_DIVIDE;
2831 case Mod:
2832 return BINARY_MODULO;
2833 case Pow:
2834 return BINARY_POWER;
2835 case LShift:
2836 return BINARY_LSHIFT;
2837 case RShift:
2838 return BINARY_RSHIFT;
2839 case BitOr:
2840 return BINARY_OR;
2841 case BitXor:
2842 return BINARY_XOR;
2843 case BitAnd:
2844 return BINARY_AND;
2845 case FloorDiv:
2846 return BINARY_FLOOR_DIVIDE;
2847 default:
2848 PyErr_Format(PyExc_SystemError,
2849 "binary op %d should not be possible", op);
2850 return 0;
2851 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852}
2853
2854static int
2855cmpop(cmpop_ty op)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 switch (op) {
2858 case Eq:
2859 return PyCmp_EQ;
2860 case NotEq:
2861 return PyCmp_NE;
2862 case Lt:
2863 return PyCmp_LT;
2864 case LtE:
2865 return PyCmp_LE;
2866 case Gt:
2867 return PyCmp_GT;
2868 case GtE:
2869 return PyCmp_GE;
2870 case Is:
2871 return PyCmp_IS;
2872 case IsNot:
2873 return PyCmp_IS_NOT;
2874 case In:
2875 return PyCmp_IN;
2876 case NotIn:
2877 return PyCmp_NOT_IN;
2878 default:
2879 return PyCmp_BAD;
2880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881}
2882
2883static int
2884inplace_binop(struct compiler *c, operator_ty op)
2885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 switch (op) {
2887 case Add:
2888 return INPLACE_ADD;
2889 case Sub:
2890 return INPLACE_SUBTRACT;
2891 case Mult:
2892 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002893 case MatMult:
2894 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 case Div:
2896 return INPLACE_TRUE_DIVIDE;
2897 case Mod:
2898 return INPLACE_MODULO;
2899 case Pow:
2900 return INPLACE_POWER;
2901 case LShift:
2902 return INPLACE_LSHIFT;
2903 case RShift:
2904 return INPLACE_RSHIFT;
2905 case BitOr:
2906 return INPLACE_OR;
2907 case BitXor:
2908 return INPLACE_XOR;
2909 case BitAnd:
2910 return INPLACE_AND;
2911 case FloorDiv:
2912 return INPLACE_FLOOR_DIVIDE;
2913 default:
2914 PyErr_Format(PyExc_SystemError,
2915 "inplace binary op %d should not be possible", op);
2916 return 0;
2917 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918}
2919
2920static int
2921compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2922{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002923 int op, scope;
2924 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 PyObject *dict = c->u->u_names;
2928 PyObject *mangled;
2929 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 mangled = _Py_Mangle(c->u->u_private, name);
2932 if (!mangled)
2933 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002934
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002935 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2936 PyUnicode_CompareWithASCIIString(name, "True") &&
2937 PyUnicode_CompareWithASCIIString(name, "False"));
2938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 op = 0;
2940 optype = OP_NAME;
2941 scope = PyST_GetScope(c->u->u_ste, mangled);
2942 switch (scope) {
2943 case FREE:
2944 dict = c->u->u_freevars;
2945 optype = OP_DEREF;
2946 break;
2947 case CELL:
2948 dict = c->u->u_cellvars;
2949 optype = OP_DEREF;
2950 break;
2951 case LOCAL:
2952 if (c->u->u_ste->ste_type == FunctionBlock)
2953 optype = OP_FAST;
2954 break;
2955 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002956 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 optype = OP_GLOBAL;
2958 break;
2959 case GLOBAL_EXPLICIT:
2960 optype = OP_GLOBAL;
2961 break;
2962 default:
2963 /* scope can be 0 */
2964 break;
2965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002968 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 switch (optype) {
2971 case OP_DEREF:
2972 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002973 case Load:
2974 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2975 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 case Store: op = STORE_DEREF; break;
2977 case AugLoad:
2978 case AugStore:
2979 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002980 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 case Param:
2982 default:
2983 PyErr_SetString(PyExc_SystemError,
2984 "param invalid for deref variable");
2985 return 0;
2986 }
2987 break;
2988 case OP_FAST:
2989 switch (ctx) {
2990 case Load: op = LOAD_FAST; break;
2991 case Store: op = STORE_FAST; break;
2992 case Del: op = DELETE_FAST; break;
2993 case AugLoad:
2994 case AugStore:
2995 break;
2996 case Param:
2997 default:
2998 PyErr_SetString(PyExc_SystemError,
2999 "param invalid for local variable");
3000 return 0;
3001 }
3002 ADDOP_O(c, op, mangled, varnames);
3003 Py_DECREF(mangled);
3004 return 1;
3005 case OP_GLOBAL:
3006 switch (ctx) {
3007 case Load: op = LOAD_GLOBAL; break;
3008 case Store: op = STORE_GLOBAL; break;
3009 case Del: op = DELETE_GLOBAL; break;
3010 case AugLoad:
3011 case AugStore:
3012 break;
3013 case Param:
3014 default:
3015 PyErr_SetString(PyExc_SystemError,
3016 "param invalid for global variable");
3017 return 0;
3018 }
3019 break;
3020 case OP_NAME:
3021 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003022 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 case Store: op = STORE_NAME; break;
3024 case Del: op = DELETE_NAME; break;
3025 case AugLoad:
3026 case AugStore:
3027 break;
3028 case Param:
3029 default:
3030 PyErr_SetString(PyExc_SystemError,
3031 "param invalid for name variable");
3032 return 0;
3033 }
3034 break;
3035 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 assert(op);
3038 arg = compiler_add_o(c, dict, mangled);
3039 Py_DECREF(mangled);
3040 if (arg < 0)
3041 return 0;
3042 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043}
3044
3045static int
3046compiler_boolop(struct compiler *c, expr_ty e)
3047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003049 int jumpi;
3050 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 assert(e->kind == BoolOp_kind);
3054 if (e->v.BoolOp.op == And)
3055 jumpi = JUMP_IF_FALSE_OR_POP;
3056 else
3057 jumpi = JUMP_IF_TRUE_OR_POP;
3058 end = compiler_new_block(c);
3059 if (end == NULL)
3060 return 0;
3061 s = e->v.BoolOp.values;
3062 n = asdl_seq_LEN(s) - 1;
3063 assert(n >= 0);
3064 for (i = 0; i < n; ++i) {
3065 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3066 ADDOP_JABS(c, jumpi, end);
3067 }
3068 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3069 compiler_use_next_block(c, end);
3070 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071}
3072
3073static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003074starunpack_helper(struct compiler *c, asdl_seq *elts,
3075 int single_op, int inner_op, int outer_op)
3076{
3077 Py_ssize_t n = asdl_seq_LEN(elts);
3078 Py_ssize_t i, nsubitems = 0, nseen = 0;
3079 for (i = 0; i < n; i++) {
3080 expr_ty elt = asdl_seq_GET(elts, i);
3081 if (elt->kind == Starred_kind) {
3082 if (nseen) {
3083 ADDOP_I(c, inner_op, nseen);
3084 nseen = 0;
3085 nsubitems++;
3086 }
3087 VISIT(c, expr, elt->v.Starred.value);
3088 nsubitems++;
3089 }
3090 else {
3091 VISIT(c, expr, elt);
3092 nseen++;
3093 }
3094 }
3095 if (nsubitems) {
3096 if (nseen) {
3097 ADDOP_I(c, inner_op, nseen);
3098 nsubitems++;
3099 }
3100 ADDOP_I(c, outer_op, nsubitems);
3101 }
3102 else
3103 ADDOP_I(c, single_op, nseen);
3104 return 1;
3105}
3106
3107static int
3108assignment_helper(struct compiler *c, asdl_seq *elts)
3109{
3110 Py_ssize_t n = asdl_seq_LEN(elts);
3111 Py_ssize_t i;
3112 int seen_star = 0;
3113 for (i = 0; i < n; i++) {
3114 expr_ty elt = asdl_seq_GET(elts, i);
3115 if (elt->kind == Starred_kind && !seen_star) {
3116 if ((i >= (1 << 8)) ||
3117 (n-i-1 >= (INT_MAX >> 8)))
3118 return compiler_error(c,
3119 "too many expressions in "
3120 "star-unpacking assignment");
3121 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3122 seen_star = 1;
3123 asdl_seq_SET(elts, i, elt->v.Starred.value);
3124 }
3125 else if (elt->kind == Starred_kind) {
3126 return compiler_error(c,
3127 "two starred expressions in assignment");
3128 }
3129 }
3130 if (!seen_star) {
3131 ADDOP_I(c, UNPACK_SEQUENCE, n);
3132 }
3133 VISIT_SEQ(c, expr, elts);
3134 return 1;
3135}
3136
3137static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138compiler_list(struct compiler *c, expr_ty e)
3139{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003140 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003142 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003144 else if (e->v.List.ctx == Load) {
3145 return starunpack_helper(c, elts,
3146 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003148 else
3149 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151}
3152
3153static int
3154compiler_tuple(struct compiler *c, expr_ty e)
3155{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003156 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003158 return assignment_helper(c, elts);
3159 }
3160 else if (e->v.Tuple.ctx == Load) {
3161 return starunpack_helper(c, elts,
3162 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3163 }
3164 else
3165 VISIT_SEQ(c, expr, elts);
3166 return 1;
3167}
3168
3169static int
3170compiler_set(struct compiler *c, expr_ty e)
3171{
3172 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3173 BUILD_SET, BUILD_SET_UNPACK);
3174}
3175
3176static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003177are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3178{
3179 Py_ssize_t i;
3180 for (i = begin; i < end; i++) {
3181 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3182 if (key == NULL || !is_const(key))
3183 return 0;
3184 }
3185 return 1;
3186}
3187
3188static int
3189compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3190{
3191 Py_ssize_t i, n = end - begin;
3192 PyObject *keys, *key;
3193 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3194 for (i = begin; i < end; i++) {
3195 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3196 }
3197 keys = PyTuple_New(n);
3198 if (keys == NULL) {
3199 return 0;
3200 }
3201 for (i = begin; i < end; i++) {
3202 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3203 Py_INCREF(key);
3204 PyTuple_SET_ITEM(keys, i - begin, key);
3205 }
3206 ADDOP_N(c, LOAD_CONST, keys, consts);
3207 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3208 }
3209 else {
3210 for (i = begin; i < end; i++) {
3211 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3212 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3213 }
3214 ADDOP_I(c, BUILD_MAP, n);
3215 }
3216 return 1;
3217}
3218
3219static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003220compiler_dict(struct compiler *c, expr_ty e)
3221{
Victor Stinner976bb402016-03-23 11:36:19 +01003222 Py_ssize_t i, n, elements;
3223 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003224 int is_unpacking = 0;
3225 n = asdl_seq_LEN(e->v.Dict.values);
3226 containers = 0;
3227 elements = 0;
3228 for (i = 0; i < n; i++) {
3229 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3230 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003231 if (!compiler_subdict(c, e, i - elements, i))
3232 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003233 containers++;
3234 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003236 if (is_unpacking) {
3237 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3238 containers++;
3239 }
3240 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003241 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 }
3243 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003244 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003245 if (!compiler_subdict(c, e, n - elements, n))
3246 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003247 containers++;
3248 }
3249 /* If there is more than one dict, they need to be merged into a new
3250 * dict. If there is one dict and it's an unpacking, then it needs
3251 * to be copied into a new dict." */
3252 while (containers > 1 || is_unpacking) {
3253 int oparg = containers < 255 ? containers : 255;
3254 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3255 containers -= (oparg - 1);
3256 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 }
3258 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259}
3260
3261static int
3262compiler_compare(struct compiler *c, expr_ty e)
3263{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003264 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3268 VISIT(c, expr, e->v.Compare.left);
3269 n = asdl_seq_LEN(e->v.Compare.ops);
3270 assert(n > 0);
3271 if (n > 1) {
3272 cleanup = compiler_new_block(c);
3273 if (cleanup == NULL)
3274 return 0;
3275 VISIT(c, expr,
3276 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3277 }
3278 for (i = 1; i < n; i++) {
3279 ADDOP(c, DUP_TOP);
3280 ADDOP(c, ROT_THREE);
3281 ADDOP_I(c, COMPARE_OP,
3282 cmpop((cmpop_ty)(asdl_seq_GET(
3283 e->v.Compare.ops, i - 1))));
3284 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3285 NEXT_BLOCK(c);
3286 if (i < (n - 1))
3287 VISIT(c, expr,
3288 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3289 }
3290 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3291 ADDOP_I(c, COMPARE_OP,
3292 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3293 if (n > 1) {
3294 basicblock *end = compiler_new_block(c);
3295 if (end == NULL)
3296 return 0;
3297 ADDOP_JREL(c, JUMP_FORWARD, end);
3298 compiler_use_next_block(c, cleanup);
3299 ADDOP(c, ROT_TWO);
3300 ADDOP(c, POP_TOP);
3301 compiler_use_next_block(c, end);
3302 }
3303 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304}
3305
3306static int
3307compiler_call(struct compiler *c, expr_ty e)
3308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 VISIT(c, expr, e->v.Call.func);
3310 return compiler_call_helper(c, 0,
3311 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003312 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003313}
3314
Eric V. Smith235a6f02015-09-19 14:51:32 -04003315static int
3316compiler_joined_str(struct compiler *c, expr_ty e)
3317{
3318 /* Concatenate parts of a string using ''.join(parts). There are
3319 probably better ways of doing this.
3320
3321 This is used for constructs like "'x=' f'{42}'", which have to
3322 be evaluated at compile time. */
3323
3324 static PyObject *empty_string;
3325 static PyObject *join_string;
3326
3327 if (!empty_string) {
3328 empty_string = PyUnicode_FromString("");
3329 if (!empty_string)
3330 return 0;
3331 }
3332 if (!join_string) {
3333 join_string = PyUnicode_FromString("join");
3334 if (!join_string)
3335 return 0;
3336 }
3337
3338 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3339 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3340 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3341 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3342 ADDOP_I(c, CALL_FUNCTION, 1);
3343 return 1;
3344}
3345
Eric V. Smitha78c7952015-11-03 12:45:05 -05003346/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003347static int
3348compiler_formatted_value(struct compiler *c, expr_ty e)
3349{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003350 /* Our oparg encodes 2 pieces of information: the conversion
3351 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003352
Eric V. Smitha78c7952015-11-03 12:45:05 -05003353 Convert the conversion char to 2 bits:
3354 None: 000 0x0 FVC_NONE
3355 !s : 001 0x1 FVC_STR
3356 !r : 010 0x2 FVC_REPR
3357 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003358
Eric V. Smitha78c7952015-11-03 12:45:05 -05003359 next bit is whether or not we have a format spec:
3360 yes : 100 0x4
3361 no : 000 0x0
3362 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003363
Eric V. Smitha78c7952015-11-03 12:45:05 -05003364 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003365
Eric V. Smitha78c7952015-11-03 12:45:05 -05003366 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003367 VISIT(c, expr, e->v.FormattedValue.value);
3368
Eric V. Smitha78c7952015-11-03 12:45:05 -05003369 switch (e->v.FormattedValue.conversion) {
3370 case 's': oparg = FVC_STR; break;
3371 case 'r': oparg = FVC_REPR; break;
3372 case 'a': oparg = FVC_ASCII; break;
3373 case -1: oparg = FVC_NONE; break;
3374 default:
3375 PyErr_SetString(PyExc_SystemError,
3376 "Unrecognized conversion character");
3377 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003378 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003379 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003380 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003381 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003382 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003383 }
3384
Eric V. Smitha78c7952015-11-03 12:45:05 -05003385 /* And push our opcode and oparg */
3386 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003387 return 1;
3388}
3389
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003390static int
3391compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3392{
3393 Py_ssize_t i, n = end - begin;
3394 keyword_ty kw;
3395 PyObject *keys, *key;
3396 assert(n > 0);
3397 if (n > 1) {
3398 for (i = begin; i < end; i++) {
3399 kw = asdl_seq_GET(keywords, i);
3400 VISIT(c, expr, kw->value);
3401 }
3402 keys = PyTuple_New(n);
3403 if (keys == NULL) {
3404 return 0;
3405 }
3406 for (i = begin; i < end; i++) {
3407 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3408 Py_INCREF(key);
3409 PyTuple_SET_ITEM(keys, i - begin, key);
3410 }
3411 ADDOP_N(c, LOAD_CONST, keys, consts);
3412 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3413 }
3414 else {
3415 /* a for loop only executes once */
3416 for (i = begin; i < end; i++) {
3417 kw = asdl_seq_GET(keywords, i);
3418 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3419 VISIT(c, expr, kw->value);
3420 }
3421 ADDOP_I(c, BUILD_MAP, n);
3422 }
3423 return 1;
3424}
3425
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003426/* shared code between compiler_call and compiler_class */
3427static int
3428compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003429 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003430 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003431 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003434 Py_ssize_t nelts, i, nseen;
3435 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003436
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003437 /* the number of tuples and dictionaries on the stack */
3438 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3439
3440 nkw = 0;
3441 nseen = 0; /* the number of positional arguments on the stack */
3442 nelts = asdl_seq_LEN(args);
3443 for (i = 0; i < nelts; i++) {
3444 expr_ty elt = asdl_seq_GET(args, i);
3445 if (elt->kind == Starred_kind) {
3446 /* A star-arg. If we've seen positional arguments,
3447 pack the positional arguments into a
3448 tuple. */
3449 if (nseen) {
3450 ADDOP_I(c, BUILD_TUPLE, nseen);
3451 nseen = 0;
3452 nsubargs++;
3453 }
3454 VISIT(c, expr, elt->v.Starred.value);
3455 nsubargs++;
3456 }
3457 else if (nsubargs) {
3458 /* We've seen star-args already, so we
3459 count towards items-to-pack-into-tuple. */
3460 VISIT(c, expr, elt);
3461 nseen++;
3462 }
3463 else {
3464 /* Positional arguments before star-arguments
3465 are left on the stack. */
3466 VISIT(c, expr, elt);
3467 n++;
3468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003470 if (nseen) {
3471 /* Pack up any trailing positional arguments. */
3472 ADDOP_I(c, BUILD_TUPLE, nseen);
3473 nsubargs++;
3474 }
3475 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003477 if (nsubargs > 1) {
3478 /* If we ended up with more than one stararg, we need
3479 to concatenate them into a single sequence. */
3480 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003483
3484 /* Same dance again for keyword arguments */
3485 nseen = 0; /* the number of keyword arguments on the stack following */
3486 nelts = asdl_seq_LEN(keywords);
3487 for (i = 0; i < nelts; i++) {
3488 keyword_ty kw = asdl_seq_GET(keywords, i);
3489 if (kw->arg == NULL) {
3490 /* A keyword argument unpacking. */
3491 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003492 if (nsubkwargs) {
3493 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3494 return 0;
3495 nsubkwargs++;
3496 }
3497 else {
3498 Py_ssize_t j;
3499 for (j = 0; j < nseen; j++) {
3500 VISIT(c, keyword, asdl_seq_GET(keywords, j));
3501 }
3502 nkw = nseen;
3503 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003504 nseen = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003505 }
3506 VISIT(c, expr, kw->value);
3507 nsubkwargs++;
3508 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003509 else {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003510 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003511 }
3512 }
3513 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003514 if (nsubkwargs) {
3515 /* Pack up any trailing keyword arguments. */
3516 if (!compiler_subkwargs(c, keywords, nelts - nseen, nelts))
3517 return 0;
3518 nsubkwargs++;
3519 }
3520 else {
3521 VISIT_SEQ(c, keyword, keywords);
3522 nkw = nseen;
3523 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003524 }
3525 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003527 if (nsubkwargs > 1) {
3528 /* Pack it all up */
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03003529 int function_pos = n + (code & 1) + 2 * nkw + 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003530 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3531 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003533 assert(n < 1<<8);
3534 assert(nkw < 1<<24);
3535 n |= nkw << 8;
3536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 switch (code) {
3538 case 0:
3539 ADDOP_I(c, CALL_FUNCTION, n);
3540 break;
3541 case 1:
3542 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3543 break;
3544 case 2:
3545 ADDOP_I(c, CALL_FUNCTION_KW, n);
3546 break;
3547 case 3:
3548 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3549 break;
3550 }
3551 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552}
3553
Nick Coghlan650f0d02007-04-15 12:05:43 +00003554
3555/* List and set comprehensions and generator expressions work by creating a
3556 nested function to perform the actual iteration. This means that the
3557 iteration variables don't leak into the current scope.
3558 The defined function is called immediately following its definition, with the
3559 result of that call being the result of the expression.
3560 The LC/SC version returns the populated container, while the GE version is
3561 flagged in symtable.c as a generator, so it returns the generator object
3562 when the function is called.
3563 This code *knows* that the loop cannot contain break, continue, or return,
3564 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3565
3566 Possible cleanups:
3567 - iterate over the generator sequence instead of using recursion
3568*/
3569
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571compiler_comprehension_generator(struct compiler *c,
3572 asdl_seq *generators, int gen_index,
3573 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 /* generate code for the iterator, then each of the ifs,
3576 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 comprehension_ty gen;
3579 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003580 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 start = compiler_new_block(c);
3583 skip = compiler_new_block(c);
3584 if_cleanup = compiler_new_block(c);
3585 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3588 anchor == NULL)
3589 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (gen_index == 0) {
3594 /* Receive outermost iter as an implicit argument */
3595 c->u->u_argcount = 1;
3596 ADDOP_I(c, LOAD_FAST, 0);
3597 }
3598 else {
3599 /* Sub-iter - calculate on the fly */
3600 VISIT(c, expr, gen->iter);
3601 ADDOP(c, GET_ITER);
3602 }
3603 compiler_use_next_block(c, start);
3604 ADDOP_JREL(c, FOR_ITER, anchor);
3605 NEXT_BLOCK(c);
3606 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* XXX this needs to be cleaned up...a lot! */
3609 n = asdl_seq_LEN(gen->ifs);
3610 for (i = 0; i < n; i++) {
3611 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3612 VISIT(c, expr, e);
3613 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3614 NEXT_BLOCK(c);
3615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 if (++gen_index < asdl_seq_LEN(generators))
3618 if (!compiler_comprehension_generator(c,
3619 generators, gen_index,
3620 elt, val, type))
3621 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 /* only append after the last for generator */
3624 if (gen_index >= asdl_seq_LEN(generators)) {
3625 /* comprehension specific code */
3626 switch (type) {
3627 case COMP_GENEXP:
3628 VISIT(c, expr, elt);
3629 ADDOP(c, YIELD_VALUE);
3630 ADDOP(c, POP_TOP);
3631 break;
3632 case COMP_LISTCOMP:
3633 VISIT(c, expr, elt);
3634 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3635 break;
3636 case COMP_SETCOMP:
3637 VISIT(c, expr, elt);
3638 ADDOP_I(c, SET_ADD, gen_index + 1);
3639 break;
3640 case COMP_DICTCOMP:
3641 /* With 'd[k] = v', v is evaluated before k, so we do
3642 the same. */
3643 VISIT(c, expr, val);
3644 VISIT(c, expr, elt);
3645 ADDOP_I(c, MAP_ADD, gen_index + 1);
3646 break;
3647 default:
3648 return 0;
3649 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 compiler_use_next_block(c, skip);
3652 }
3653 compiler_use_next_block(c, if_cleanup);
3654 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3655 compiler_use_next_block(c, anchor);
3656
3657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
3660static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003661compiler_comprehension(struct compiler *c, expr_ty e, int type,
3662 identifier name, asdl_seq *generators, expr_ty elt,
3663 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 PyCodeObject *co = NULL;
3666 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003667 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 outermost_iter = ((comprehension_ty)
3670 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003671
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003672 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3673 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 if (type != COMP_GENEXP) {
3677 int op;
3678 switch (type) {
3679 case COMP_LISTCOMP:
3680 op = BUILD_LIST;
3681 break;
3682 case COMP_SETCOMP:
3683 op = BUILD_SET;
3684 break;
3685 case COMP_DICTCOMP:
3686 op = BUILD_MAP;
3687 break;
3688 default:
3689 PyErr_Format(PyExc_SystemError,
3690 "unknown comprehension type %d", type);
3691 goto error_in_scope;
3692 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 ADDOP_I(c, op, 0);
3695 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (!compiler_comprehension_generator(c, generators, 0, elt,
3698 val, type))
3699 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 if (type != COMP_GENEXP) {
3702 ADDOP(c, RETURN_VALUE);
3703 }
3704
3705 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003706 qualname = c->u->u_qualname;
3707 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003709 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 goto error;
3711
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003712 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003714 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 Py_DECREF(co);
3716
3717 VISIT(c, expr, outermost_iter);
3718 ADDOP(c, GET_ITER);
3719 ADDOP_I(c, CALL_FUNCTION, 1);
3720 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003721error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003723error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003724 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 Py_XDECREF(co);
3726 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003727}
3728
3729static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003730compiler_genexp(struct compiler *c, expr_ty e)
3731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 static identifier name;
3733 if (!name) {
3734 name = PyUnicode_FromString("<genexpr>");
3735 if (!name)
3736 return 0;
3737 }
3738 assert(e->kind == GeneratorExp_kind);
3739 return compiler_comprehension(c, e, COMP_GENEXP, name,
3740 e->v.GeneratorExp.generators,
3741 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742}
3743
3744static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003745compiler_listcomp(struct compiler *c, expr_ty e)
3746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 static identifier name;
3748 if (!name) {
3749 name = PyUnicode_FromString("<listcomp>");
3750 if (!name)
3751 return 0;
3752 }
3753 assert(e->kind == ListComp_kind);
3754 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3755 e->v.ListComp.generators,
3756 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003757}
3758
3759static int
3760compiler_setcomp(struct compiler *c, expr_ty e)
3761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 static identifier name;
3763 if (!name) {
3764 name = PyUnicode_FromString("<setcomp>");
3765 if (!name)
3766 return 0;
3767 }
3768 assert(e->kind == SetComp_kind);
3769 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3770 e->v.SetComp.generators,
3771 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003772}
3773
3774
3775static int
3776compiler_dictcomp(struct compiler *c, expr_ty e)
3777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 static identifier name;
3779 if (!name) {
3780 name = PyUnicode_FromString("<dictcomp>");
3781 if (!name)
3782 return 0;
3783 }
3784 assert(e->kind == DictComp_kind);
3785 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3786 e->v.DictComp.generators,
3787 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003788}
3789
3790
3791static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792compiler_visit_keyword(struct compiler *c, keyword_ty k)
3793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3795 VISIT(c, expr, k->value);
3796 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797}
3798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 whether they are true or false.
3801
3802 Return values: 1 for true, 0 for false, -1 for non-constant.
3803 */
3804
3805static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003806expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 char *id;
3809 switch (e->kind) {
3810 case Ellipsis_kind:
3811 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003812 case Constant_kind:
3813 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 case Num_kind:
3815 return PyObject_IsTrue(e->v.Num.n);
3816 case Str_kind:
3817 return PyObject_IsTrue(e->v.Str.s);
3818 case Name_kind:
3819 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003821 if (id && strcmp(id, "__debug__") == 0)
3822 return !c->c_optimize;
3823 return -1;
3824 case NameConstant_kind: {
3825 PyObject *o = e->v.NameConstant.value;
3826 if (o == Py_None)
3827 return 0;
3828 else if (o == Py_True)
3829 return 1;
3830 else if (o == Py_False)
3831 return 0;
3832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 default:
3834 return -1;
3835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836}
3837
Yury Selivanov75445082015-05-11 22:57:16 -04003838
3839/*
3840 Implements the async with statement.
3841
3842 The semantics outlined in that PEP are as follows:
3843
3844 async with EXPR as VAR:
3845 BLOCK
3846
3847 It is implemented roughly as:
3848
3849 context = EXPR
3850 exit = context.__aexit__ # not calling it
3851 value = await context.__aenter__()
3852 try:
3853 VAR = value # if VAR present in the syntax
3854 BLOCK
3855 finally:
3856 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003857 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003858 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003859 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003860 if not (await exit(*exc)):
3861 raise
3862 */
3863static int
3864compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3865{
3866 basicblock *block, *finally;
3867 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3868
3869 assert(s->kind == AsyncWith_kind);
3870
3871 block = compiler_new_block(c);
3872 finally = compiler_new_block(c);
3873 if (!block || !finally)
3874 return 0;
3875
3876 /* Evaluate EXPR */
3877 VISIT(c, expr, item->context_expr);
3878
3879 ADDOP(c, BEFORE_ASYNC_WITH);
3880 ADDOP(c, GET_AWAITABLE);
3881 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3882 ADDOP(c, YIELD_FROM);
3883
3884 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3885
3886 /* SETUP_ASYNC_WITH pushes a finally block. */
3887 compiler_use_next_block(c, block);
3888 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3889 return 0;
3890 }
3891
3892 if (item->optional_vars) {
3893 VISIT(c, expr, item->optional_vars);
3894 }
3895 else {
3896 /* Discard result from context.__aenter__() */
3897 ADDOP(c, POP_TOP);
3898 }
3899
3900 pos++;
3901 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3902 /* BLOCK code */
3903 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3904 else if (!compiler_async_with(c, s, pos))
3905 return 0;
3906
3907 /* End of try block; start the finally block */
3908 ADDOP(c, POP_BLOCK);
3909 compiler_pop_fblock(c, FINALLY_TRY, block);
3910
3911 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3912 compiler_use_next_block(c, finally);
3913 if (!compiler_push_fblock(c, FINALLY_END, finally))
3914 return 0;
3915
3916 /* Finally block starts; context.__exit__ is on the stack under
3917 the exception or return information. Just issue our magic
3918 opcode. */
3919 ADDOP(c, WITH_CLEANUP_START);
3920
3921 ADDOP(c, GET_AWAITABLE);
3922 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3923 ADDOP(c, YIELD_FROM);
3924
3925 ADDOP(c, WITH_CLEANUP_FINISH);
3926
3927 /* Finally block ends. */
3928 ADDOP(c, END_FINALLY);
3929 compiler_pop_fblock(c, FINALLY_END, finally);
3930 return 1;
3931}
3932
3933
Guido van Rossumc2e20742006-02-27 22:32:47 +00003934/*
3935 Implements the with statement from PEP 343.
3936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003938
3939 with EXPR as VAR:
3940 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941
Guido van Rossumc2e20742006-02-27 22:32:47 +00003942 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943
Thomas Wouters477c8d52006-05-27 19:21:47 +00003944 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003945 exit = context.__exit__ # not calling it
3946 value = context.__enter__()
3947 try:
3948 VAR = value # if VAR present in the syntax
3949 BLOCK
3950 finally:
3951 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003952 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003953 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003954 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003955 exit(*exc)
3956 */
3957static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003958compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003959{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003960 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003961 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003962
3963 assert(s->kind == With_kind);
3964
Guido van Rossumc2e20742006-02-27 22:32:47 +00003965 block = compiler_new_block(c);
3966 finally = compiler_new_block(c);
3967 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003968 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003969
Thomas Wouters477c8d52006-05-27 19:21:47 +00003970 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003971 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003972 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003973
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003974 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003975 compiler_use_next_block(c, block);
3976 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003977 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003978 }
3979
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003980 if (item->optional_vars) {
3981 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003982 }
3983 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003985 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003986 }
3987
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003988 pos++;
3989 if (pos == asdl_seq_LEN(s->v.With.items))
3990 /* BLOCK code */
3991 VISIT_SEQ(c, stmt, s->v.With.body)
3992 else if (!compiler_with(c, s, pos))
3993 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003994
3995 /* End of try block; start the finally block */
3996 ADDOP(c, POP_BLOCK);
3997 compiler_pop_fblock(c, FINALLY_TRY, block);
3998
3999 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4000 compiler_use_next_block(c, finally);
4001 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004002 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004003
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004004 /* Finally block starts; context.__exit__ is on the stack under
4005 the exception or return information. Just issue our magic
4006 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004007 ADDOP(c, WITH_CLEANUP_START);
4008 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004009
4010 /* Finally block ends. */
4011 ADDOP(c, END_FINALLY);
4012 compiler_pop_fblock(c, FINALLY_END, finally);
4013 return 1;
4014}
4015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016static int
4017compiler_visit_expr(struct compiler *c, expr_ty e)
4018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 /* If expr e has a different line number than the last expr/stmt,
4020 set a new line number for the next instruction.
4021 */
4022 if (e->lineno > c->u->u_lineno) {
4023 c->u->u_lineno = e->lineno;
4024 c->u->u_lineno_set = 0;
4025 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004026 /* Updating the column offset is always harmless. */
4027 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 switch (e->kind) {
4029 case BoolOp_kind:
4030 return compiler_boolop(c, e);
4031 case BinOp_kind:
4032 VISIT(c, expr, e->v.BinOp.left);
4033 VISIT(c, expr, e->v.BinOp.right);
4034 ADDOP(c, binop(c, e->v.BinOp.op));
4035 break;
4036 case UnaryOp_kind:
4037 VISIT(c, expr, e->v.UnaryOp.operand);
4038 ADDOP(c, unaryop(e->v.UnaryOp.op));
4039 break;
4040 case Lambda_kind:
4041 return compiler_lambda(c, e);
4042 case IfExp_kind:
4043 return compiler_ifexp(c, e);
4044 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004045 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004047 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 case GeneratorExp_kind:
4049 return compiler_genexp(c, e);
4050 case ListComp_kind:
4051 return compiler_listcomp(c, e);
4052 case SetComp_kind:
4053 return compiler_setcomp(c, e);
4054 case DictComp_kind:
4055 return compiler_dictcomp(c, e);
4056 case Yield_kind:
4057 if (c->u->u_ste->ste_type != FunctionBlock)
4058 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004059 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4060 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004061 if (e->v.Yield.value) {
4062 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 }
4064 else {
4065 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4066 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004067 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004069 case YieldFrom_kind:
4070 if (c->u->u_ste->ste_type != FunctionBlock)
4071 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004072
4073 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4074 return compiler_error(c, "'yield from' inside async function");
4075
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004076 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004077 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004078 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4079 ADDOP(c, YIELD_FROM);
4080 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004081 case Await_kind:
4082 if (c->u->u_ste->ste_type != FunctionBlock)
4083 return compiler_error(c, "'await' outside function");
4084
Yury Selivanov9dec0352015-06-30 12:49:04 -04004085 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
4086 return compiler_error(
4087 c, "'await' expressions in comprehensions are not supported");
4088
Yury Selivanov75445082015-05-11 22:57:16 -04004089 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
4090 return compiler_error(c, "'await' outside async function");
4091
4092 VISIT(c, expr, e->v.Await.value);
4093 ADDOP(c, GET_AWAITABLE);
4094 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4095 ADDOP(c, YIELD_FROM);
4096 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 case Compare_kind:
4098 return compiler_compare(c, e);
4099 case Call_kind:
4100 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004101 case Constant_kind:
4102 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4103 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 case Num_kind:
4105 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4106 break;
4107 case Str_kind:
4108 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4109 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004110 case JoinedStr_kind:
4111 return compiler_joined_str(c, e);
4112 case FormattedValue_kind:
4113 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 case Bytes_kind:
4115 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4116 break;
4117 case Ellipsis_kind:
4118 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4119 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004120 case NameConstant_kind:
4121 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4122 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* The following exprs can be assignment targets. */
4124 case Attribute_kind:
4125 if (e->v.Attribute.ctx != AugStore)
4126 VISIT(c, expr, e->v.Attribute.value);
4127 switch (e->v.Attribute.ctx) {
4128 case AugLoad:
4129 ADDOP(c, DUP_TOP);
4130 /* Fall through to load */
4131 case Load:
4132 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4133 break;
4134 case AugStore:
4135 ADDOP(c, ROT_TWO);
4136 /* Fall through to save */
4137 case Store:
4138 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4139 break;
4140 case Del:
4141 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4142 break;
4143 case Param:
4144 default:
4145 PyErr_SetString(PyExc_SystemError,
4146 "param invalid in attribute expression");
4147 return 0;
4148 }
4149 break;
4150 case Subscript_kind:
4151 switch (e->v.Subscript.ctx) {
4152 case AugLoad:
4153 VISIT(c, expr, e->v.Subscript.value);
4154 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4155 break;
4156 case Load:
4157 VISIT(c, expr, e->v.Subscript.value);
4158 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4159 break;
4160 case AugStore:
4161 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4162 break;
4163 case Store:
4164 VISIT(c, expr, e->v.Subscript.value);
4165 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4166 break;
4167 case Del:
4168 VISIT(c, expr, e->v.Subscript.value);
4169 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4170 break;
4171 case Param:
4172 default:
4173 PyErr_SetString(PyExc_SystemError,
4174 "param invalid in subscript expression");
4175 return 0;
4176 }
4177 break;
4178 case Starred_kind:
4179 switch (e->v.Starred.ctx) {
4180 case Store:
4181 /* In all legitimate cases, the Starred node was already replaced
4182 * by compiler_list/compiler_tuple. XXX: is that okay? */
4183 return compiler_error(c,
4184 "starred assignment target must be in a list or tuple");
4185 default:
4186 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004187 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 }
4189 break;
4190 case Name_kind:
4191 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4192 /* child nodes of List and Tuple will have expr_context set */
4193 case List_kind:
4194 return compiler_list(c, e);
4195 case Tuple_kind:
4196 return compiler_tuple(c, e);
4197 }
4198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199}
4200
4201static int
4202compiler_augassign(struct compiler *c, stmt_ty s)
4203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 expr_ty e = s->v.AugAssign.target;
4205 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 switch (e->kind) {
4210 case Attribute_kind:
4211 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4212 AugLoad, e->lineno, e->col_offset, c->c_arena);
4213 if (auge == NULL)
4214 return 0;
4215 VISIT(c, expr, auge);
4216 VISIT(c, expr, s->v.AugAssign.value);
4217 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4218 auge->v.Attribute.ctx = AugStore;
4219 VISIT(c, expr, auge);
4220 break;
4221 case Subscript_kind:
4222 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4223 AugLoad, e->lineno, e->col_offset, c->c_arena);
4224 if (auge == NULL)
4225 return 0;
4226 VISIT(c, expr, auge);
4227 VISIT(c, expr, s->v.AugAssign.value);
4228 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4229 auge->v.Subscript.ctx = AugStore;
4230 VISIT(c, expr, auge);
4231 break;
4232 case Name_kind:
4233 if (!compiler_nameop(c, e->v.Name.id, Load))
4234 return 0;
4235 VISIT(c, expr, s->v.AugAssign.value);
4236 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4237 return compiler_nameop(c, e->v.Name.id, Store);
4238 default:
4239 PyErr_Format(PyExc_SystemError,
4240 "invalid node type (%d) for augmented assignment",
4241 e->kind);
4242 return 0;
4243 }
4244 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245}
4246
4247static int
4248compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 struct fblockinfo *f;
4251 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4252 PyErr_SetString(PyExc_SystemError,
4253 "too many statically nested blocks");
4254 return 0;
4255 }
4256 f = &c->u->u_fblock[c->u->u_nfblocks++];
4257 f->fb_type = t;
4258 f->fb_block = b;
4259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260}
4261
4262static void
4263compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 struct compiler_unit *u = c->u;
4266 assert(u->u_nfblocks > 0);
4267 u->u_nfblocks--;
4268 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4269 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004270}
4271
Thomas Wouters89f507f2006-12-13 04:49:30 +00004272static int
4273compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 int i;
4275 struct compiler_unit *u = c->u;
4276 for (i = 0; i < u->u_nfblocks; ++i) {
4277 if (u->u_fblock[i].fb_type == LOOP)
4278 return 1;
4279 }
4280 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004281}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004282/* Raises a SyntaxError and returns 0.
4283 If something goes wrong, a different exception may be raised.
4284*/
4285
4286static int
4287compiler_error(struct compiler *c, const char *errstr)
4288{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004289 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291
Victor Stinner14e461d2013-08-26 22:28:21 +02004292 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (!loc) {
4294 Py_INCREF(Py_None);
4295 loc = Py_None;
4296 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004297 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004298 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 if (!u)
4300 goto exit;
4301 v = Py_BuildValue("(zO)", errstr, u);
4302 if (!v)
4303 goto exit;
4304 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004305 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 Py_DECREF(loc);
4307 Py_XDECREF(u);
4308 Py_XDECREF(v);
4309 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310}
4311
4312static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313compiler_handle_subscr(struct compiler *c, const char *kind,
4314 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 /* XXX this code is duplicated */
4319 switch (ctx) {
4320 case AugLoad: /* fall through to Load */
4321 case Load: op = BINARY_SUBSCR; break;
4322 case AugStore:/* fall through to Store */
4323 case Store: op = STORE_SUBSCR; break;
4324 case Del: op = DELETE_SUBSCR; break;
4325 case Param:
4326 PyErr_Format(PyExc_SystemError,
4327 "invalid %s kind %d in subscript\n",
4328 kind, ctx);
4329 return 0;
4330 }
4331 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004332 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 }
4334 else if (ctx == AugStore) {
4335 ADDOP(c, ROT_THREE);
4336 }
4337 ADDOP(c, op);
4338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004339}
4340
4341static int
4342compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 int n = 2;
4345 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 /* only handles the cases where BUILD_SLICE is emitted */
4348 if (s->v.Slice.lower) {
4349 VISIT(c, expr, s->v.Slice.lower);
4350 }
4351 else {
4352 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (s->v.Slice.upper) {
4356 VISIT(c, expr, s->v.Slice.upper);
4357 }
4358 else {
4359 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4360 }
4361
4362 if (s->v.Slice.step) {
4363 n++;
4364 VISIT(c, expr, s->v.Slice.step);
4365 }
4366 ADDOP_I(c, BUILD_SLICE, n);
4367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368}
4369
4370static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4372 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 switch (s->kind) {
4375 case Slice_kind:
4376 return compiler_slice(c, s, ctx);
4377 case Index_kind:
4378 VISIT(c, expr, s->v.Index.value);
4379 break;
4380 case ExtSlice_kind:
4381 default:
4382 PyErr_SetString(PyExc_SystemError,
4383 "extended slice invalid in nested slice");
4384 return 0;
4385 }
4386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387}
4388
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389static int
4390compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 char * kindname = NULL;
4393 switch (s->kind) {
4394 case Index_kind:
4395 kindname = "index";
4396 if (ctx != AugStore) {
4397 VISIT(c, expr, s->v.Index.value);
4398 }
4399 break;
4400 case Slice_kind:
4401 kindname = "slice";
4402 if (ctx != AugStore) {
4403 if (!compiler_slice(c, s, ctx))
4404 return 0;
4405 }
4406 break;
4407 case ExtSlice_kind:
4408 kindname = "extended slice";
4409 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004410 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 for (i = 0; i < n; i++) {
4412 slice_ty sub = (slice_ty)asdl_seq_GET(
4413 s->v.ExtSlice.dims, i);
4414 if (!compiler_visit_nested_slice(c, sub, ctx))
4415 return 0;
4416 }
4417 ADDOP_I(c, BUILD_TUPLE, n);
4418 }
4419 break;
4420 default:
4421 PyErr_Format(PyExc_SystemError,
4422 "invalid subscript kind %d", s->kind);
4423 return 0;
4424 }
4425 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426}
4427
Thomas Wouters89f507f2006-12-13 04:49:30 +00004428/* End of the compiler section, beginning of the assembler section */
4429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430/* do depth-first search of basic block graph, starting with block.
4431 post records the block indices in post-order.
4432
4433 XXX must handle implicit jumps from one block to next
4434*/
4435
Thomas Wouters89f507f2006-12-13 04:49:30 +00004436struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 PyObject *a_bytecode; /* string containing bytecode */
4438 int a_offset; /* offset into bytecode */
4439 int a_nblocks; /* number of reachable blocks */
4440 basicblock **a_postorder; /* list of blocks in dfs postorder */
4441 PyObject *a_lnotab; /* string containing lnotab */
4442 int a_lnotab_off; /* offset into lnotab */
4443 int a_lineno; /* last lineno of emitted instruction */
4444 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004445};
4446
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447static void
4448dfs(struct compiler *c, basicblock *b, struct assembler *a)
4449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 int i;
4451 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 if (b->b_seen)
4454 return;
4455 b->b_seen = 1;
4456 if (b->b_next != NULL)
4457 dfs(c, b->b_next, a);
4458 for (i = 0; i < b->b_iused; i++) {
4459 instr = &b->b_instr[i];
4460 if (instr->i_jrel || instr->i_jabs)
4461 dfs(c, instr->i_target, a);
4462 }
4463 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004464}
4465
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004466static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4468{
Larry Hastings3a907972013-11-23 14:49:22 -08004469 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 struct instr *instr;
4471 if (b->b_seen || b->b_startdepth >= depth)
4472 return maxdepth;
4473 b->b_seen = 1;
4474 b->b_startdepth = depth;
4475 for (i = 0; i < b->b_iused; i++) {
4476 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004477 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4478 if (effect == PY_INVALID_STACK_EFFECT) {
4479 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4480 Py_FatalError("PyCompile_OpcodeStackEffect()");
4481 }
4482 depth += effect;
4483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 if (depth > maxdepth)
4485 maxdepth = depth;
4486 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4487 if (instr->i_jrel || instr->i_jabs) {
4488 target_depth = depth;
4489 if (instr->i_opcode == FOR_ITER) {
4490 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004491 }
4492 else if (instr->i_opcode == SETUP_FINALLY ||
4493 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 target_depth = depth+3;
4495 if (target_depth > maxdepth)
4496 maxdepth = target_depth;
4497 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004498 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4499 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4500 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 maxdepth = stackdepth_walk(c, instr->i_target,
4502 target_depth, maxdepth);
4503 if (instr->i_opcode == JUMP_ABSOLUTE ||
4504 instr->i_opcode == JUMP_FORWARD) {
4505 goto out; /* remaining code is dead */
4506 }
4507 }
4508 }
4509 if (b->b_next)
4510 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004511out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 b->b_seen = 0;
4513 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514}
4515
4516/* Find the flow path that needs the largest stack. We assume that
4517 * cycles in the flow graph have no net effect on the stack depth.
4518 */
4519static int
4520stackdepth(struct compiler *c)
4521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 basicblock *b, *entryblock;
4523 entryblock = NULL;
4524 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4525 b->b_seen = 0;
4526 b->b_startdepth = INT_MIN;
4527 entryblock = b;
4528 }
4529 if (!entryblock)
4530 return 0;
4531 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004532}
4533
4534static int
4535assemble_init(struct assembler *a, int nblocks, int firstlineno)
4536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 memset(a, 0, sizeof(struct assembler));
4538 a->a_lineno = firstlineno;
4539 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4540 if (!a->a_bytecode)
4541 return 0;
4542 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4543 if (!a->a_lnotab)
4544 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004545 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 PyErr_NoMemory();
4547 return 0;
4548 }
4549 a->a_postorder = (basicblock **)PyObject_Malloc(
4550 sizeof(basicblock *) * nblocks);
4551 if (!a->a_postorder) {
4552 PyErr_NoMemory();
4553 return 0;
4554 }
4555 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004556}
4557
4558static void
4559assemble_free(struct assembler *a)
4560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 Py_XDECREF(a->a_bytecode);
4562 Py_XDECREF(a->a_lnotab);
4563 if (a->a_postorder)
4564 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004565}
4566
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004567static int
4568blocksize(basicblock *b)
4569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 int i;
4571 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004574 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004576}
4577
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004578/* Appends a pair to the end of the line number table, a_lnotab, representing
4579 the instruction's bytecode offset and line number. See
4580 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004581
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004582static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004583assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004586 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 d_bytecode = a->a_offset - a->a_lineno_off;
4590 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 if(d_bytecode == 0 && d_lineno == 0)
4595 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 if (d_bytecode > 255) {
4598 int j, nbytes, ncodes = d_bytecode / 255;
4599 nbytes = a->a_lnotab_off + 2 * ncodes;
4600 len = PyBytes_GET_SIZE(a->a_lnotab);
4601 if (nbytes >= len) {
4602 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4603 len = nbytes;
4604 else if (len <= INT_MAX / 2)
4605 len *= 2;
4606 else {
4607 PyErr_NoMemory();
4608 return 0;
4609 }
4610 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4611 return 0;
4612 }
4613 lnotab = (unsigned char *)
4614 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4615 for (j = 0; j < ncodes; j++) {
4616 *lnotab++ = 255;
4617 *lnotab++ = 0;
4618 }
4619 d_bytecode -= ncodes * 255;
4620 a->a_lnotab_off += ncodes * 2;
4621 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004622 assert(0 <= d_bytecode && d_bytecode <= 255);
4623
4624 if (d_lineno < -128 || 127 < d_lineno) {
4625 int j, nbytes, ncodes, k;
4626 if (d_lineno < 0) {
4627 k = -128;
4628 /* use division on positive numbers */
4629 ncodes = (-d_lineno) / 128;
4630 }
4631 else {
4632 k = 127;
4633 ncodes = d_lineno / 127;
4634 }
4635 d_lineno -= ncodes * k;
4636 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 nbytes = a->a_lnotab_off + 2 * ncodes;
4638 len = PyBytes_GET_SIZE(a->a_lnotab);
4639 if (nbytes >= len) {
4640 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4641 len = nbytes;
4642 else if (len <= INT_MAX / 2)
4643 len *= 2;
4644 else {
4645 PyErr_NoMemory();
4646 return 0;
4647 }
4648 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4649 return 0;
4650 }
4651 lnotab = (unsigned char *)
4652 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4653 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004654 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 d_bytecode = 0;
4656 for (j = 1; j < ncodes; j++) {
4657 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004658 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 a->a_lnotab_off += ncodes * 2;
4661 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004662 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 len = PyBytes_GET_SIZE(a->a_lnotab);
4665 if (a->a_lnotab_off + 2 >= len) {
4666 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4667 return 0;
4668 }
4669 lnotab = (unsigned char *)
4670 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 a->a_lnotab_off += 2;
4673 if (d_bytecode) {
4674 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004675 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 }
4677 else { /* First line of a block; def stmt, etc. */
4678 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004679 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 }
4681 a->a_lineno = i->i_lineno;
4682 a->a_lineno_off = a->a_offset;
4683 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004684}
4685
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004686/* assemble_emit()
4687 Extend the bytecode with a new instruction.
4688 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004689*/
4690
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004692assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004693{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004694 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4696 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004697
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004698 arg = i->i_oparg;
4699 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 if (i->i_lineno && !assemble_lnotab(a, i))
4701 return 0;
4702 if (a->a_offset + size >= len) {
4703 if (len > PY_SSIZE_T_MAX / 2)
4704 return 0;
4705 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4706 return 0;
4707 }
4708 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4709 a->a_offset += size;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004710 write_op_arg((unsigned char*)code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004712}
4713
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004714static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004718 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 /* Compute the size of each block and fixup jump args.
4722 Replace block pointer with position in bytecode. */
4723 do {
4724 totsize = 0;
4725 for (i = a->a_nblocks - 1; i >= 0; i--) {
4726 b = a->a_postorder[i];
4727 bsize = blocksize(b);
4728 b->b_offset = totsize;
4729 totsize += bsize;
4730 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004731 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4733 bsize = b->b_offset;
4734 for (i = 0; i < b->b_iused; i++) {
4735 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004736 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 /* Relative jumps are computed relative to
4738 the instruction pointer after fetching
4739 the jump instruction.
4740 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004741 bsize += isize;
4742 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004744 if (instr->i_jrel) {
4745 instr->i_oparg -= bsize;
4746 }
4747 if (instrsize(instr->i_oparg) != isize) {
4748 extended_arg_recompile = 1;
4749 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 }
4752 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 /* XXX: This is an awful hack that could hurt performance, but
4755 on the bright side it should work until we come up
4756 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 The issue is that in the first loop blocksize() is called
4759 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004760 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 So we loop until we stop seeing new EXTENDED_ARGs.
4764 The only EXTENDED_ARGs that could be popping up are
4765 ones in jump instructions. So this should converge
4766 fairly quickly.
4767 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004768 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004769}
4770
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004771static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004772dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 PyObject *tuple, *k, *v;
4775 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 tuple = PyTuple_New(size);
4778 if (tuple == NULL)
4779 return NULL;
4780 while (PyDict_Next(dict, &pos, &k, &v)) {
4781 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004782 /* The keys of the dictionary are tuples. (see compiler_add_o
4783 * and _PyCode_ConstantKey). The object we want is always second,
4784 * though. */
4785 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 Py_INCREF(k);
4787 assert((i - offset) < size);
4788 assert((i - offset) >= 0);
4789 PyTuple_SET_ITEM(tuple, i - offset, k);
4790 }
4791 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004792}
4793
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004794static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004795compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004798 int flags = 0;
4799 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004801 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 if (ste->ste_nested)
4803 flags |= CO_NESTED;
4804 if (ste->ste_generator)
4805 flags |= CO_GENERATOR;
4806 if (ste->ste_varargs)
4807 flags |= CO_VARARGS;
4808 if (ste->ste_varkeywords)
4809 flags |= CO_VARKEYWORDS;
4810 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 /* (Only) inherit compilerflags in PyCF_MASK */
4813 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 n = PyDict_Size(c->u->u_freevars);
4816 if (n < 0)
4817 return -1;
4818 if (n == 0) {
4819 n = PyDict_Size(c->u->u_cellvars);
4820 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004821 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004823 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 }
4825 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004828}
4829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004830static PyCodeObject *
4831makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 PyObject *tmp;
4834 PyCodeObject *co = NULL;
4835 PyObject *consts = NULL;
4836 PyObject *names = NULL;
4837 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 PyObject *name = NULL;
4839 PyObject *freevars = NULL;
4840 PyObject *cellvars = NULL;
4841 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004842 Py_ssize_t nlocals;
4843 int nlocals_int;
4844 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004845 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 tmp = dict_keys_inorder(c->u->u_consts, 0);
4848 if (!tmp)
4849 goto error;
4850 consts = PySequence_List(tmp); /* optimize_code requires a list */
4851 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 names = dict_keys_inorder(c->u->u_names, 0);
4854 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4855 if (!consts || !names || !varnames)
4856 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4859 if (!cellvars)
4860 goto error;
4861 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4862 if (!freevars)
4863 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004866 assert(nlocals < INT_MAX);
4867 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 flags = compute_code_flags(c);
4870 if (flags < 0)
4871 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4874 if (!bytecode)
4875 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4878 if (!tmp)
4879 goto error;
4880 Py_DECREF(consts);
4881 consts = tmp;
4882
Victor Stinnerf8e32212013-11-19 23:56:34 +01004883 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4884 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4885 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004886 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 bytecode, consts, names, varnames,
4888 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004889 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 c->u->u_firstlineno,
4891 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004892 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 Py_XDECREF(consts);
4894 Py_XDECREF(names);
4895 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 Py_XDECREF(name);
4897 Py_XDECREF(freevars);
4898 Py_XDECREF(cellvars);
4899 Py_XDECREF(bytecode);
4900 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004901}
4902
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004903
4904/* For debugging purposes only */
4905#if 0
4906static void
4907dump_instr(const struct instr *i)
4908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 const char *jrel = i->i_jrel ? "jrel " : "";
4910 const char *jabs = i->i_jabs ? "jabs " : "";
4911 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004914 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4918 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004919}
4920
4921static void
4922dump_basicblock(const basicblock *b)
4923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 const char *seen = b->b_seen ? "seen " : "";
4925 const char *b_return = b->b_return ? "return " : "";
4926 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4927 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4928 if (b->b_instr) {
4929 int i;
4930 for (i = 0; i < b->b_iused; i++) {
4931 fprintf(stderr, " [%02d] ", i);
4932 dump_instr(b->b_instr + i);
4933 }
4934 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004935}
4936#endif
4937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004938static PyCodeObject *
4939assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 basicblock *b, *entryblock;
4942 struct assembler a;
4943 int i, j, nblocks;
4944 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 /* Make sure every block that falls off the end returns None.
4947 XXX NEXT_BLOCK() isn't quite right, because if the last
4948 block ends with a jump or return b_next shouldn't set.
4949 */
4950 if (!c->u->u_curblock->b_return) {
4951 NEXT_BLOCK(c);
4952 if (addNone)
4953 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4954 ADDOP(c, RETURN_VALUE);
4955 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 nblocks = 0;
4958 entryblock = NULL;
4959 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4960 nblocks++;
4961 entryblock = b;
4962 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 /* Set firstlineno if it wasn't explicitly set. */
4965 if (!c->u->u_firstlineno) {
4966 if (entryblock && entryblock->b_instr)
4967 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4968 else
4969 c->u->u_firstlineno = 1;
4970 }
4971 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4972 goto error;
4973 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 /* Can't modify the bytecode after computing jump offsets. */
4976 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 /* Emit code in reverse postorder from dfs. */
4979 for (i = a.a_nblocks - 1; i >= 0; i--) {
4980 b = a.a_postorder[i];
4981 for (j = 0; j < b->b_iused; j++)
4982 if (!assemble_emit(&a, &b->b_instr[j]))
4983 goto error;
4984 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4987 goto error;
4988 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4989 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004992 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 assemble_free(&a);
4994 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004995}
Georg Brandl8334fd92010-12-04 10:26:46 +00004996
4997#undef PyAST_Compile
4998PyAPI_FUNC(PyCodeObject *)
4999PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5000 PyArena *arena)
5001{
5002 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5003}