blob: 45e4262b40822f42ae7016592ede63dbd534e5ca [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) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700479 assert((uintptr_t)block != 0xcbcbcbcbU);
480 assert((uintptr_t)block != 0xfbfbfbfbU);
481 assert((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
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700807 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 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:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300973 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400975 case BUILD_LIST_UNPACK:
976 case BUILD_TUPLE_UNPACK:
977 case BUILD_SET_UNPACK:
978 case BUILD_MAP_UNPACK:
979 return 1 - oparg;
980 case BUILD_MAP_UNPACK_WITH_CALL:
981 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700983 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300984 case BUILD_CONST_KEY_MAP:
985 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case LOAD_ATTR:
987 return 0;
988 case COMPARE_OP:
989 return -1;
990 case IMPORT_NAME:
991 return -1;
992 case IMPORT_FROM:
993 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case JUMP_FORWARD:
996 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
997 case JUMP_IF_FALSE_OR_POP: /* "" */
998 case JUMP_ABSOLUTE:
999 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case POP_JUMP_IF_FALSE:
1002 case POP_JUMP_IF_TRUE:
1003 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case LOAD_GLOBAL:
1006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case CONTINUE_LOOP:
1009 return 0;
1010 case SETUP_LOOP:
1011 return 0;
1012 case SETUP_EXCEPT:
1013 case SETUP_FINALLY:
1014 return 6; /* can push 3 values for the new exception
1015 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case LOAD_FAST:
1018 return 1;
1019 case STORE_FAST:
1020 return -1;
1021 case DELETE_FAST:
1022 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case RAISE_VARARGS:
1025 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001026#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case CALL_FUNCTION:
1028 return -NARGS(oparg);
1029 case CALL_FUNCTION_VAR:
1030 case CALL_FUNCTION_KW:
1031 return -NARGS(oparg)-1;
1032 case CALL_FUNCTION_VAR_KW:
1033 return -NARGS(oparg)-2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001034#undef NARGS
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001035 case MAKE_FUNCTION:
1036 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1037 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case BUILD_SLICE:
1039 if (oparg == 3)
1040 return -2;
1041 else
1042 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case LOAD_CLOSURE:
1045 return 1;
1046 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001047 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return 1;
1049 case STORE_DEREF:
1050 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001051 case DELETE_DEREF:
1052 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001053 case GET_AWAITABLE:
1054 return 0;
1055 case SETUP_ASYNC_WITH:
1056 return 6;
1057 case BEFORE_ASYNC_WITH:
1058 return 1;
1059 case GET_AITER:
1060 return 0;
1061 case GET_ANEXT:
1062 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001063 case GET_YIELD_FROM_ITER:
1064 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001065 case FORMAT_VALUE:
1066 /* If there's a fmt_spec on the stack, we go from 2->1,
1067 else 1->1. */
1068 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001070 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
Larry Hastings3a907972013-11-23 14:49:22 -08001072 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075/* Add an opcode with no argument.
1076 Returns 0 on failure, 1 on success.
1077*/
1078
1079static int
1080compiler_addop(struct compiler *c, int opcode)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 basicblock *b;
1083 struct instr *i;
1084 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001085 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 off = compiler_next_instr(c, c->u->u_curblock);
1087 if (off < 0)
1088 return 0;
1089 b = c->u->u_curblock;
1090 i = &b->b_instr[off];
1091 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001092 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (opcode == RETURN_VALUE)
1094 b->b_return = 1;
1095 compiler_set_lineno(c, off);
1096 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097}
1098
Victor Stinnerf8e32212013-11-19 23:56:34 +01001099static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001100compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyObject *t, *v;
1103 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104
Victor Stinnerefb24132016-01-22 12:33:12 +01001105 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (t == NULL)
1107 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 v = PyDict_GetItem(dict, t);
1110 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001111 if (PyErr_Occurred()) {
1112 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001116 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (!v) {
1118 Py_DECREF(t);
1119 return -1;
1120 }
1121 if (PyDict_SetItem(dict, t, v) < 0) {
1122 Py_DECREF(t);
1123 Py_DECREF(v);
1124 return -1;
1125 }
1126 Py_DECREF(v);
1127 }
1128 else
1129 arg = PyLong_AsLong(v);
1130 Py_DECREF(t);
1131 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
1134static int
1135compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001138 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001140 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 return compiler_addop_i(c, opcode, arg);
1142}
1143
1144static int
1145compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001148 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1150 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001151 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 arg = compiler_add_o(c, dict, mangled);
1153 Py_DECREF(mangled);
1154 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return compiler_addop_i(c, opcode, arg);
1157}
1158
1159/* Add an opcode with an integer argument.
1160 Returns 0 on failure, 1 on success.
1161*/
1162
1163static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001164compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 struct instr *i;
1167 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001168
Victor Stinner2ad474b2016-03-01 23:34:47 +01001169 /* oparg value is unsigned, but a signed C int is usually used to store
1170 it in the C code (like Python/ceval.c).
1171
1172 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1173
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001174 The argument of a concrete bytecode instruction is limited to 8-bit.
1175 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1176 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001177 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 off = compiler_next_instr(c, c->u->u_curblock);
1180 if (off < 0)
1181 return 0;
1182 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001183 i->i_opcode = opcode;
1184 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 compiler_set_lineno(c, off);
1186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187}
1188
1189static int
1190compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 struct instr *i;
1193 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001195 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 assert(b != NULL);
1197 off = compiler_next_instr(c, c->u->u_curblock);
1198 if (off < 0)
1199 return 0;
1200 i = &c->u->u_curblock->b_instr[off];
1201 i->i_opcode = opcode;
1202 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (absolute)
1204 i->i_jabs = 1;
1205 else
1206 i->i_jrel = 1;
1207 compiler_set_lineno(c, off);
1208 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209}
1210
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001211/* NEXT_BLOCK() creates an implicit jump from the current block
1212 to the new block.
1213
1214 The returns inside this macro make it impossible to decref objects
1215 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (compiler_next_block((C)) == NULL) \
1219 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220}
1221
1222#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (!compiler_addop((C), (OP))) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001227#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!compiler_addop((C), (OP))) { \
1229 compiler_exit_scope(c); \
1230 return 0; \
1231 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001232}
1233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1236 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237}
1238
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001239/* Same as ADDOP_O, but steals a reference. */
1240#define ADDOP_N(C, OP, O, TYPE) { \
1241 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1242 Py_DECREF((O)); \
1243 return 0; \
1244 } \
1245 Py_DECREF((O)); \
1246}
1247
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1250 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (!compiler_addop_i((C), (OP), (O))) \
1255 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256}
1257
1258#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_j((C), (OP), (O), 1)) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_j((C), (OP), (O), 0)) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1269 the ASDL name to synthesize the name of the C type and the visit function.
1270*/
1271
1272#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_visit_ ## TYPE((C), (V))) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001277#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!compiler_visit_ ## TYPE((C), (V))) { \
1279 compiler_exit_scope(c); \
1280 return 0; \
1281 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001282}
1283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_visit_slice((C), (V), (CTX))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 int _i; \
1291 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1292 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1293 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1294 if (!compiler_visit_ ## TYPE((C), elt)) \
1295 return 0; \
1296 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001299#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int _i; \
1301 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1302 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1303 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1304 if (!compiler_visit_ ## TYPE((C), elt)) { \
1305 compiler_exit_scope(c); \
1306 return 0; \
1307 } \
1308 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001309}
1310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311static int
1312compiler_isdocstring(stmt_ty s)
1313{
1314 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001315 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001316 if (s->v.Expr.value->kind == Str_kind)
1317 return 1;
1318 if (s->v.Expr.value->kind == Constant_kind)
1319 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1320 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321}
1322
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001323static int
1324is_const(expr_ty e)
1325{
1326 switch (e->kind) {
1327 case Constant_kind:
1328 case Num_kind:
1329 case Str_kind:
1330 case Bytes_kind:
1331 case Ellipsis_kind:
1332 case NameConstant_kind:
1333 return 1;
1334 default:
1335 return 0;
1336 }
1337}
1338
1339static PyObject *
1340get_const_value(expr_ty e)
1341{
1342 switch (e->kind) {
1343 case Constant_kind:
1344 return e->v.Constant.value;
1345 case Num_kind:
1346 return e->v.Num.n;
1347 case Str_kind:
1348 return e->v.Str.s;
1349 case Bytes_kind:
1350 return e->v.Bytes.s;
1351 case Ellipsis_kind:
1352 return Py_Ellipsis;
1353 case NameConstant_kind:
1354 return e->v.NameConstant.value;
1355 default:
1356 assert(!is_const(e));
1357 return NULL;
1358 }
1359}
1360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361/* Compile a sequence of statements, checking for a docstring. */
1362
1363static int
1364compiler_body(struct compiler *c, asdl_seq *stmts)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 int i = 0;
1367 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (!asdl_seq_LEN(stmts))
1370 return 1;
1371 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001372 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* don't generate docstrings if -OO */
1374 i = 1;
1375 VISIT(c, expr, st->v.Expr.value);
1376 if (!compiler_nameop(c, __doc__, Store))
1377 return 0;
1378 }
1379 for (; i < asdl_seq_LEN(stmts); i++)
1380 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1381 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382}
1383
1384static PyCodeObject *
1385compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyCodeObject *co;
1388 int addNone = 1;
1389 static PyObject *module;
1390 if (!module) {
1391 module = PyUnicode_InternFromString("<module>");
1392 if (!module)
1393 return NULL;
1394 }
1395 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001396 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 return NULL;
1398 switch (mod->kind) {
1399 case Module_kind:
1400 if (!compiler_body(c, mod->v.Module.body)) {
1401 compiler_exit_scope(c);
1402 return 0;
1403 }
1404 break;
1405 case Interactive_kind:
1406 c->c_interactive = 1;
1407 VISIT_SEQ_IN_SCOPE(c, stmt,
1408 mod->v.Interactive.body);
1409 break;
1410 case Expression_kind:
1411 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1412 addNone = 0;
1413 break;
1414 case Suite_kind:
1415 PyErr_SetString(PyExc_SystemError,
1416 "suite should not be possible");
1417 return 0;
1418 default:
1419 PyErr_Format(PyExc_SystemError,
1420 "module kind %d should not be possible",
1421 mod->kind);
1422 return 0;
1423 }
1424 co = assemble(c, addNone);
1425 compiler_exit_scope(c);
1426 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001427}
1428
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429/* The test for LOCAL must come before the test for FREE in order to
1430 handle classes where name is both local and free. The local var is
1431 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001432*/
1433
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434static int
1435get_ref_type(struct compiler *c, PyObject *name)
1436{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001437 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001438 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1439 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1440 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001441 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (scope == 0) {
1443 char buf[350];
1444 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001445 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001447 PyUnicode_AsUTF8(name),
1448 PyUnicode_AsUTF8(c->u->u_name),
1449 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1450 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1451 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1452 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 );
1454 Py_FatalError(buf);
1455 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458}
1459
1460static int
1461compiler_lookup_arg(PyObject *dict, PyObject *name)
1462{
1463 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001464 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001466 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001468 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001470 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001471 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472}
1473
1474static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001475compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001477 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001478 if (qualname == NULL)
1479 qualname = co->co_name;
1480
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001481 if (free) {
1482 for (i = 0; i < free; ++i) {
1483 /* Bypass com_addop_varname because it will generate
1484 LOAD_DEREF but LOAD_CLOSURE is needed.
1485 */
1486 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1487 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001489 /* Special case: If a class contains a method with a
1490 free variable that has the same name as a method,
1491 the name will be considered free *and* local in the
1492 class. It should be handled by the closure, as
1493 well as by the normal name loookup logic.
1494 */
1495 reftype = get_ref_type(c, name);
1496 if (reftype == CELL)
1497 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1498 else /* (reftype == FREE) */
1499 arg = compiler_lookup_arg(c->u->u_freevars, name);
1500 if (arg == -1) {
1501 fprintf(stderr,
1502 "lookup %s in %s %d %d\n"
1503 "freevars of %s: %s\n",
1504 PyUnicode_AsUTF8(PyObject_Repr(name)),
1505 PyUnicode_AsUTF8(c->u->u_name),
1506 reftype, arg,
1507 PyUnicode_AsUTF8(co->co_name),
1508 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1509 Py_FatalError("compiler_make_closure()");
1510 }
1511 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001513 flags |= 0x08;
1514 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001517 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001518 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
1522static int
1523compiler_decorators(struct compiler *c, asdl_seq* decos)
1524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (!decos)
1528 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1531 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1532 }
1533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001537compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001539{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001540 /* Push a dict of keyword-only default values.
1541
1542 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1543 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001544 int i;
1545 PyObject *keys = NULL;
1546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1548 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1549 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1550 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001551 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001552 if (!mangled) {
1553 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001555 if (keys == NULL) {
1556 keys = PyList_New(1);
1557 if (keys == NULL) {
1558 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001559 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001560 }
1561 PyList_SET_ITEM(keys, 0, mangled);
1562 }
1563 else {
1564 int res = PyList_Append(keys, mangled);
1565 Py_DECREF(mangled);
1566 if (res == -1) {
1567 goto error;
1568 }
1569 }
1570 if (!compiler_visit_expr(c, default_)) {
1571 goto error;
1572 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
1574 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001575 if (keys != NULL) {
1576 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1577 PyObject *keys_tuple = PyList_AsTuple(keys);
1578 Py_DECREF(keys);
1579 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001580 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001581 }
1582 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1583 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001584 assert(default_count > 0);
1585 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001586 }
1587 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001588 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001589 }
1590
1591error:
1592 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001593 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001594}
1595
1596static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001597compiler_visit_argannotation(struct compiler *c, identifier id,
1598 expr_ty annotation, PyObject *names)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001601 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001603 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001604 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001605 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001606 if (PyList_Append(names, mangled) < 0) {
1607 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001608 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001609 }
1610 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001612 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001613}
1614
1615static int
1616compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1617 PyObject *names)
1618{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001619 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 for (i = 0; i < asdl_seq_LEN(args); i++) {
1621 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001622 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 c,
1624 arg->arg,
1625 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001626 names))
1627 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001629 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001630}
1631
1632static int
1633compiler_visit_annotations(struct compiler *c, arguments_ty args,
1634 expr_ty returns)
1635{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001636 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001637 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001638
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001639 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 */
1641 static identifier return_str;
1642 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001643 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 names = PyList_New(0);
1645 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001646 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001647
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001648 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001650 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001651 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001652 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001654 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001656 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001657 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001658 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (!return_str) {
1662 return_str = PyUnicode_InternFromString("return");
1663 if (!return_str)
1664 goto error;
1665 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001666 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 goto error;
1668 }
1669
1670 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001672 PyObject *keytuple = PyList_AsTuple(names);
1673 Py_DECREF(names);
1674 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001675 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001677 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1678 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001679 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001681 else {
1682 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001683 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001684 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001685
1686error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001688 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001689}
1690
1691static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001692compiler_visit_defaults(struct compiler *c, arguments_ty args)
1693{
1694 VISIT_SEQ(c, expr, args->defaults);
1695 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1696 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697}
1698
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001699static Py_ssize_t
1700compiler_default_arguments(struct compiler *c, arguments_ty args)
1701{
1702 Py_ssize_t funcflags = 0;
1703 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001704 if (!compiler_visit_defaults(c, args))
1705 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001706 funcflags |= 0x01;
1707 }
1708 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001709 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001710 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001711 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001712 return -1;
1713 }
1714 else if (res > 0) {
1715 funcflags |= 0x02;
1716 }
1717 }
1718 return funcflags;
1719}
1720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721static int
Yury Selivanov75445082015-05-11 22:57:16 -04001722compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001725 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001726 arguments_ty args;
1727 expr_ty returns;
1728 identifier name;
1729 asdl_seq* decos;
1730 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001732 Py_ssize_t i, n, funcflags;
1733 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001734 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001735 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736
Yury Selivanov75445082015-05-11 22:57:16 -04001737 if (is_async) {
1738 assert(s->kind == AsyncFunctionDef_kind);
1739
1740 args = s->v.AsyncFunctionDef.args;
1741 returns = s->v.AsyncFunctionDef.returns;
1742 decos = s->v.AsyncFunctionDef.decorator_list;
1743 name = s->v.AsyncFunctionDef.name;
1744 body = s->v.AsyncFunctionDef.body;
1745
1746 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1747 } else {
1748 assert(s->kind == FunctionDef_kind);
1749
1750 args = s->v.FunctionDef.args;
1751 returns = s->v.FunctionDef.returns;
1752 decos = s->v.FunctionDef.decorator_list;
1753 name = s->v.FunctionDef.name;
1754 body = s->v.FunctionDef.body;
1755
1756 scope_type = COMPILER_SCOPE_FUNCTION;
1757 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (!compiler_decorators(c, decos))
1760 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001761
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001762 funcflags = compiler_default_arguments(c, args);
1763 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001765 }
1766
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001767 annotations = compiler_visit_annotations(c, args, returns);
1768 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001769 return 0;
1770 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001772 funcflags |= 0x04;
1773 }
1774
1775 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1776 return 0;
1777 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778
Yury Selivanov75445082015-05-11 22:57:16 -04001779 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001781 if (docstring && c->c_optimize < 2) {
1782 if (st->v.Expr.value->kind == Constant_kind)
1783 first_const = st->v.Expr.value->v.Constant.value;
1784 else
1785 first_const = st->v.Expr.value->v.Str.s;
1786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1788 compiler_exit_scope(c);
1789 return 0;
1790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 c->u->u_argcount = asdl_seq_LEN(args->args);
1793 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001794 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* if there was a docstring, we need to skip the first statement */
1796 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001797 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 VISIT_IN_SCOPE(c, stmt, st);
1799 }
1800 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001801 qualname = c->u->u_qualname;
1802 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001804 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001805 Py_XDECREF(qualname);
1806 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001808 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809
Yury Selivanovb7666a32015-07-22 14:48:57 +03001810 if (is_async)
1811 co->co_flags |= CO_COROUTINE;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001812 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001813 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 /* decorators */
1817 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1818 ADDOP_I(c, CALL_FUNCTION, 1);
1819 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820
Yury Selivanov75445082015-05-11 22:57:16 -04001821 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822}
1823
1824static int
1825compiler_class(struct compiler *c, stmt_ty s)
1826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyCodeObject *co;
1828 PyObject *str;
1829 int i;
1830 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (!compiler_decorators(c, decos))
1833 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* ultimately generate code for:
1836 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1837 where:
1838 <func> is a function/closure created from the class body;
1839 it has a single argument (__locals__) where the dict
1840 (or MutableSequence) representing the locals is passed
1841 <name> is the class name
1842 <bases> is the positional arguments and *varargs argument
1843 <keywords> is the keyword arguments and **kwds argument
1844 This borrows from compiler_call.
1845 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001848 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1849 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 0;
1851 /* this block represents what we do in the new scope */
1852 {
1853 /* use the class name for name mangling */
1854 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001855 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 /* load (global) __name__ ... */
1857 str = PyUnicode_InternFromString("__name__");
1858 if (!str || !compiler_nameop(c, str, Load)) {
1859 Py_XDECREF(str);
1860 compiler_exit_scope(c);
1861 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001862 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_DECREF(str);
1864 /* ... and store it as __module__ */
1865 str = PyUnicode_InternFromString("__module__");
1866 if (!str || !compiler_nameop(c, str, Store)) {
1867 Py_XDECREF(str);
1868 compiler_exit_scope(c);
1869 return 0;
1870 }
1871 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001872 assert(c->u->u_qualname);
1873 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001874 str = PyUnicode_InternFromString("__qualname__");
1875 if (!str || !compiler_nameop(c, str, Store)) {
1876 Py_XDECREF(str);
1877 compiler_exit_scope(c);
1878 return 0;
1879 }
1880 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* compile the body proper */
1882 if (!compiler_body(c, s->v.ClassDef.body)) {
1883 compiler_exit_scope(c);
1884 return 0;
1885 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001886 if (c->u->u_ste->ste_needs_class_closure) {
1887 /* return the (empty) __class__ cell */
1888 str = PyUnicode_InternFromString("__class__");
1889 if (str == NULL) {
1890 compiler_exit_scope(c);
1891 return 0;
1892 }
1893 i = compiler_lookup_arg(c->u->u_cellvars, str);
1894 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001895 if (i < 0) {
1896 compiler_exit_scope(c);
1897 return 0;
1898 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001899 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* Return the cell where to store __class__ */
1901 ADDOP_I(c, LOAD_CLOSURE, i);
1902 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001903 else {
1904 assert(PyDict_Size(c->u->u_cellvars) == 0);
1905 /* This happens when nobody references the cell. Return None. */
1906 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1909 /* create the code object */
1910 co = assemble(c, 1);
1911 }
1912 /* leave the new scope */
1913 compiler_exit_scope(c);
1914 if (co == NULL)
1915 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 /* 2. load the 'build_class' function */
1918 ADDOP(c, LOAD_BUILD_CLASS);
1919
1920 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001921 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 Py_DECREF(co);
1923
1924 /* 4. load class name */
1925 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1926
1927 /* 5. generate the rest of the code for the call */
1928 if (!compiler_call_helper(c, 2,
1929 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001930 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 return 0;
1932
1933 /* 6. apply decorators */
1934 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1935 ADDOP_I(c, CALL_FUNCTION, 1);
1936 }
1937
1938 /* 7. store into <name> */
1939 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1940 return 0;
1941 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942}
1943
1944static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001945compiler_ifexp(struct compiler *c, expr_ty e)
1946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 basicblock *end, *next;
1948
1949 assert(e->kind == IfExp_kind);
1950 end = compiler_new_block(c);
1951 if (end == NULL)
1952 return 0;
1953 next = compiler_new_block(c);
1954 if (next == NULL)
1955 return 0;
1956 VISIT(c, expr, e->v.IfExp.test);
1957 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1958 VISIT(c, expr, e->v.IfExp.body);
1959 ADDOP_JREL(c, JUMP_FORWARD, end);
1960 compiler_use_next_block(c, next);
1961 VISIT(c, expr, e->v.IfExp.orelse);
1962 compiler_use_next_block(c, end);
1963 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001964}
1965
1966static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967compiler_lambda(struct compiler *c, expr_ty e)
1968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001970 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001972 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 arguments_ty args = e->v.Lambda.args;
1974 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!name) {
1977 name = PyUnicode_InternFromString("<lambda>");
1978 if (!name)
1979 return 0;
1980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001982 funcflags = compiler_default_arguments(c, args);
1983 if (funcflags == -1) {
1984 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001987 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001988 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* Make None the first constant, so the lambda can't have a
1992 docstring. */
1993 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1994 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 c->u->u_argcount = asdl_seq_LEN(args->args);
1997 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1998 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1999 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002000 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
2002 else {
2003 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002004 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002006 qualname = c->u->u_qualname;
2007 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002009 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002013 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 Py_DECREF(co);
2015
2016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017}
2018
2019static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020compiler_if(struct compiler *c, stmt_ty s)
2021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 basicblock *end, *next;
2023 int constant;
2024 assert(s->kind == If_kind);
2025 end = compiler_new_block(c);
2026 if (end == NULL)
2027 return 0;
2028
Georg Brandl8334fd92010-12-04 10:26:46 +00002029 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* constant = 0: "if 0"
2031 * constant = 1: "if 1", "if 2", ...
2032 * constant = -1: rest */
2033 if (constant == 0) {
2034 if (s->v.If.orelse)
2035 VISIT_SEQ(c, stmt, s->v.If.orelse);
2036 } else if (constant == 1) {
2037 VISIT_SEQ(c, stmt, s->v.If.body);
2038 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002039 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 next = compiler_new_block(c);
2041 if (next == NULL)
2042 return 0;
2043 }
2044 else
2045 next = end;
2046 VISIT(c, expr, s->v.If.test);
2047 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2048 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002049 if (asdl_seq_LEN(s->v.If.orelse)) {
2050 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 compiler_use_next_block(c, next);
2052 VISIT_SEQ(c, stmt, s->v.If.orelse);
2053 }
2054 }
2055 compiler_use_next_block(c, end);
2056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057}
2058
2059static int
2060compiler_for(struct compiler *c, stmt_ty s)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 start = compiler_new_block(c);
2065 cleanup = compiler_new_block(c);
2066 end = compiler_new_block(c);
2067 if (start == NULL || end == NULL || cleanup == NULL)
2068 return 0;
2069 ADDOP_JREL(c, SETUP_LOOP, end);
2070 if (!compiler_push_fblock(c, LOOP, start))
2071 return 0;
2072 VISIT(c, expr, s->v.For.iter);
2073 ADDOP(c, GET_ITER);
2074 compiler_use_next_block(c, start);
2075 ADDOP_JREL(c, FOR_ITER, cleanup);
2076 VISIT(c, expr, s->v.For.target);
2077 VISIT_SEQ(c, stmt, s->v.For.body);
2078 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2079 compiler_use_next_block(c, cleanup);
2080 ADDOP(c, POP_BLOCK);
2081 compiler_pop_fblock(c, LOOP, start);
2082 VISIT_SEQ(c, stmt, s->v.For.orelse);
2083 compiler_use_next_block(c, end);
2084 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085}
2086
Yury Selivanov75445082015-05-11 22:57:16 -04002087
2088static int
2089compiler_async_for(struct compiler *c, stmt_ty s)
2090{
2091 static PyObject *stopiter_error = NULL;
2092 basicblock *try, *except, *end, *after_try, *try_cleanup,
2093 *after_loop, *after_loop_else;
2094
2095 if (stopiter_error == NULL) {
2096 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2097 if (stopiter_error == NULL)
2098 return 0;
2099 }
2100
2101 try = compiler_new_block(c);
2102 except = compiler_new_block(c);
2103 end = compiler_new_block(c);
2104 after_try = compiler_new_block(c);
2105 try_cleanup = compiler_new_block(c);
2106 after_loop = compiler_new_block(c);
2107 after_loop_else = compiler_new_block(c);
2108
2109 if (try == NULL || except == NULL || end == NULL
2110 || after_try == NULL || try_cleanup == NULL)
2111 return 0;
2112
2113 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2114 if (!compiler_push_fblock(c, LOOP, try))
2115 return 0;
2116
2117 VISIT(c, expr, s->v.AsyncFor.iter);
2118 ADDOP(c, GET_AITER);
2119 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2120 ADDOP(c, YIELD_FROM);
2121
2122 compiler_use_next_block(c, try);
2123
2124
2125 ADDOP_JREL(c, SETUP_EXCEPT, except);
2126 if (!compiler_push_fblock(c, EXCEPT, try))
2127 return 0;
2128
2129 ADDOP(c, GET_ANEXT);
2130 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2131 ADDOP(c, YIELD_FROM);
2132 VISIT(c, expr, s->v.AsyncFor.target);
2133 ADDOP(c, POP_BLOCK);
2134 compiler_pop_fblock(c, EXCEPT, try);
2135 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2136
2137
2138 compiler_use_next_block(c, except);
2139 ADDOP(c, DUP_TOP);
2140 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2141 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2142 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2143
2144 ADDOP(c, POP_TOP);
2145 ADDOP(c, POP_TOP);
2146 ADDOP(c, POP_TOP);
2147 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2148 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2149 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2150
2151
2152 compiler_use_next_block(c, try_cleanup);
2153 ADDOP(c, END_FINALLY);
2154
2155 compiler_use_next_block(c, after_try);
2156 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2157 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2158
2159 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2160 compiler_pop_fblock(c, LOOP, try);
2161
2162 compiler_use_next_block(c, after_loop);
2163 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2164
2165 compiler_use_next_block(c, after_loop_else);
2166 VISIT_SEQ(c, stmt, s->v.For.orelse);
2167
2168 compiler_use_next_block(c, end);
2169
2170 return 1;
2171}
2172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173static int
2174compiler_while(struct compiler *c, stmt_ty s)
2175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002177 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (constant == 0) {
2180 if (s->v.While.orelse)
2181 VISIT_SEQ(c, stmt, s->v.While.orelse);
2182 return 1;
2183 }
2184 loop = compiler_new_block(c);
2185 end = compiler_new_block(c);
2186 if (constant == -1) {
2187 anchor = compiler_new_block(c);
2188 if (anchor == NULL)
2189 return 0;
2190 }
2191 if (loop == NULL || end == NULL)
2192 return 0;
2193 if (s->v.While.orelse) {
2194 orelse = compiler_new_block(c);
2195 if (orelse == NULL)
2196 return 0;
2197 }
2198 else
2199 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 ADDOP_JREL(c, SETUP_LOOP, end);
2202 compiler_use_next_block(c, loop);
2203 if (!compiler_push_fblock(c, LOOP, loop))
2204 return 0;
2205 if (constant == -1) {
2206 VISIT(c, expr, s->v.While.test);
2207 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2208 }
2209 VISIT_SEQ(c, stmt, s->v.While.body);
2210 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* XXX should the two POP instructions be in a separate block
2213 if there is no else clause ?
2214 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002216 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002218 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 compiler_pop_fblock(c, LOOP, loop);
2220 if (orelse != NULL) /* what if orelse is just pass? */
2221 VISIT_SEQ(c, stmt, s->v.While.orelse);
2222 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225}
2226
2227static int
2228compiler_continue(struct compiler *c)
2229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2231 static const char IN_FINALLY_ERROR_MSG[] =
2232 "'continue' not supported inside 'finally' clause";
2233 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 if (!c->u->u_nfblocks)
2236 return compiler_error(c, LOOP_ERROR_MSG);
2237 i = c->u->u_nfblocks - 1;
2238 switch (c->u->u_fblock[i].fb_type) {
2239 case LOOP:
2240 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2241 break;
2242 case EXCEPT:
2243 case FINALLY_TRY:
2244 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2245 /* Prevent continue anywhere under a finally
2246 even if hidden in a sub-try or except. */
2247 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2248 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2249 }
2250 if (i == -1)
2251 return compiler_error(c, LOOP_ERROR_MSG);
2252 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2253 break;
2254 case FINALLY_END:
2255 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2256 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259}
2260
2261/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262
2263 SETUP_FINALLY L
2264 <code for body>
2265 POP_BLOCK
2266 LOAD_CONST <None>
2267 L: <code for finalbody>
2268 END_FINALLY
2269
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 The special instructions use the block stack. Each block
2271 stack entry contains the instruction that created it (here
2272 SETUP_FINALLY), the level of the value stack at the time the
2273 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 Pushes the current value stack level and the label
2277 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 Pops en entry from the block stack, and pops the value
2280 stack until its level is the same as indicated on the
2281 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 Pops a variable number of entries from the *value* stack
2284 and re-raises the exception they specify. The number of
2285 entries popped depends on the (pseudo) exception type.
2286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 The block stack is unwound when an exception is raised:
2288 when a SETUP_FINALLY entry is found, the exception is pushed
2289 onto the value stack (and the exception condition is cleared),
2290 and the interpreter jumps to the label gotten from the block
2291 stack.
2292*/
2293
2294static int
2295compiler_try_finally(struct compiler *c, stmt_ty s)
2296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 basicblock *body, *end;
2298 body = compiler_new_block(c);
2299 end = compiler_new_block(c);
2300 if (body == NULL || end == NULL)
2301 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 ADDOP_JREL(c, SETUP_FINALLY, end);
2304 compiler_use_next_block(c, body);
2305 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2306 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002307 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2308 if (!compiler_try_except(c, s))
2309 return 0;
2310 }
2311 else {
2312 VISIT_SEQ(c, stmt, s->v.Try.body);
2313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 ADDOP(c, POP_BLOCK);
2315 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2318 compiler_use_next_block(c, end);
2319 if (!compiler_push_fblock(c, FINALLY_END, end))
2320 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002321 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 ADDOP(c, END_FINALLY);
2323 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326}
2327
2328/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002329 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 (The contents of the value stack is shown in [], with the top
2331 at the right; 'tb' is trace-back info, 'val' the exception's
2332 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333
2334 Value stack Label Instruction Argument
2335 [] SETUP_EXCEPT L1
2336 [] <code for S>
2337 [] POP_BLOCK
2338 [] JUMP_FORWARD L0
2339
2340 [tb, val, exc] L1: DUP )
2341 [tb, val, exc, exc] <evaluate E1> )
2342 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2343 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2344 [tb, val, exc] POP
2345 [tb, val] <assign to V1> (or POP if no V1)
2346 [tb] POP
2347 [] <code for S1>
2348 JUMP_FORWARD L0
2349
2350 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351 .............................etc.......................
2352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2354
2355 [] L0: <next statement>
2356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 Of course, parts are not generated if Vi or Ei is not present.
2358*/
2359static int
2360compiler_try_except(struct compiler *c, stmt_ty s)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002363 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 body = compiler_new_block(c);
2366 except = compiler_new_block(c);
2367 orelse = compiler_new_block(c);
2368 end = compiler_new_block(c);
2369 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2370 return 0;
2371 ADDOP_JREL(c, SETUP_EXCEPT, except);
2372 compiler_use_next_block(c, body);
2373 if (!compiler_push_fblock(c, EXCEPT, body))
2374 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002375 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 ADDOP(c, POP_BLOCK);
2377 compiler_pop_fblock(c, EXCEPT, body);
2378 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002379 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 compiler_use_next_block(c, except);
2381 for (i = 0; i < n; i++) {
2382 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002383 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (!handler->v.ExceptHandler.type && i < n-1)
2385 return compiler_error(c, "default 'except:' must be last");
2386 c->u->u_lineno_set = 0;
2387 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002388 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 except = compiler_new_block(c);
2390 if (except == NULL)
2391 return 0;
2392 if (handler->v.ExceptHandler.type) {
2393 ADDOP(c, DUP_TOP);
2394 VISIT(c, expr, handler->v.ExceptHandler.type);
2395 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2396 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2397 }
2398 ADDOP(c, POP_TOP);
2399 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002400 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002401
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002402 cleanup_end = compiler_new_block(c);
2403 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002404 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002405 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002406
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002407 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2408 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002410 /*
2411 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002412 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002413 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002414 try:
2415 # body
2416 finally:
2417 name = None
2418 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002419 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002421 /* second try: */
2422 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2423 compiler_use_next_block(c, cleanup_body);
2424 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2425 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002427 /* second # body */
2428 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2429 ADDOP(c, POP_BLOCK);
2430 ADDOP(c, POP_EXCEPT);
2431 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002433 /* finally: */
2434 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2435 compiler_use_next_block(c, cleanup_end);
2436 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2437 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002439 /* name = None */
2440 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2441 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002443 /* del name */
2444 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002446 ADDOP(c, END_FINALLY);
2447 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 }
2449 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002450 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002452 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002453 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002454 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455
Guido van Rossumb940e112007-01-10 16:19:56 +00002456 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002457 ADDOP(c, POP_TOP);
2458 compiler_use_next_block(c, cleanup_body);
2459 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2460 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002462 ADDOP(c, POP_EXCEPT);
2463 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 }
2465 ADDOP_JREL(c, JUMP_FORWARD, end);
2466 compiler_use_next_block(c, except);
2467 }
2468 ADDOP(c, END_FINALLY);
2469 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002470 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 compiler_use_next_block(c, end);
2472 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473}
2474
2475static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002476compiler_try(struct compiler *c, stmt_ty s) {
2477 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2478 return compiler_try_finally(c, s);
2479 else
2480 return compiler_try_except(c, s);
2481}
2482
2483
2484static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485compiler_import_as(struct compiler *c, identifier name, identifier asname)
2486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* The IMPORT_NAME opcode was already generated. This function
2488 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 If there is a dot in name, we need to split it and emit a
2491 LOAD_ATTR for each name.
2492 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2494 PyUnicode_GET_LENGTH(name), 1);
2495 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002496 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002499 Py_ssize_t pos = dot + 1;
2500 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 dot = PyUnicode_FindChar(name, '.', pos,
2503 PyUnicode_GET_LENGTH(name), 1);
2504 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002505 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 attr = PyUnicode_Substring(name, pos,
2507 (dot != -1) ? dot :
2508 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002510 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 ADDOP_O(c, LOAD_ATTR, attr, names);
2512 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002513 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 }
2515 }
2516 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517}
2518
2519static int
2520compiler_import(struct compiler *c, stmt_ty s)
2521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 /* The Import node stores a module name like a.b.c as a single
2523 string. This is convenient for all cases except
2524 import a.b.c as d
2525 where we need to parse that string to extract the individual
2526 module names.
2527 XXX Perhaps change the representation to make this case simpler?
2528 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002529 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 for (i = 0; i < n; i++) {
2532 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2533 int r;
2534 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 level = PyLong_FromLong(0);
2537 if (level == NULL)
2538 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 ADDOP_O(c, LOAD_CONST, level, consts);
2541 Py_DECREF(level);
2542 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2543 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 if (alias->asname) {
2546 r = compiler_import_as(c, alias->name, alias->asname);
2547 if (!r)
2548 return r;
2549 }
2550 else {
2551 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002552 Py_ssize_t dot = PyUnicode_FindChar(
2553 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002554 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002556 if (tmp == NULL)
2557 return 0;
2558 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 Py_DECREF(tmp);
2562 }
2563 if (!r)
2564 return r;
2565 }
2566 }
2567 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568}
2569
2570static int
2571compiler_from_import(struct compiler *c, stmt_ty s)
2572{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002573 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyObject *names = PyTuple_New(n);
2576 PyObject *level;
2577 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 if (!empty_string) {
2580 empty_string = PyUnicode_FromString("");
2581 if (!empty_string)
2582 return 0;
2583 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 if (!names)
2586 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 level = PyLong_FromLong(s->v.ImportFrom.level);
2589 if (!level) {
2590 Py_DECREF(names);
2591 return 0;
2592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 /* build up the names */
2595 for (i = 0; i < n; i++) {
2596 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2597 Py_INCREF(alias->name);
2598 PyTuple_SET_ITEM(names, i, alias->name);
2599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2602 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2603 Py_DECREF(level);
2604 Py_DECREF(names);
2605 return compiler_error(c, "from __future__ imports must occur "
2606 "at the beginning of the file");
2607 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 ADDOP_O(c, LOAD_CONST, level, consts);
2610 Py_DECREF(level);
2611 ADDOP_O(c, LOAD_CONST, names, consts);
2612 Py_DECREF(names);
2613 if (s->v.ImportFrom.module) {
2614 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2615 }
2616 else {
2617 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2618 }
2619 for (i = 0; i < n; i++) {
2620 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2621 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 assert(n == 1);
2625 ADDOP(c, IMPORT_STAR);
2626 return 1;
2627 }
2628
2629 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2630 store_name = alias->name;
2631 if (alias->asname)
2632 store_name = alias->asname;
2633
2634 if (!compiler_nameop(c, store_name, Store)) {
2635 Py_DECREF(names);
2636 return 0;
2637 }
2638 }
2639 /* remove imported module */
2640 ADDOP(c, POP_TOP);
2641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642}
2643
2644static int
2645compiler_assert(struct compiler *c, stmt_ty s)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 static PyObject *assertion_error = NULL;
2648 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002649 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650
Georg Brandl8334fd92010-12-04 10:26:46 +00002651 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return 1;
2653 if (assertion_error == NULL) {
2654 assertion_error = PyUnicode_InternFromString("AssertionError");
2655 if (assertion_error == NULL)
2656 return 0;
2657 }
2658 if (s->v.Assert.test->kind == Tuple_kind &&
2659 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002660 msg = PyUnicode_FromString("assertion is always true, "
2661 "perhaps remove parentheses?");
2662 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002664 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2665 c->c_filename, c->u->u_lineno,
2666 NULL, NULL) == -1) {
2667 Py_DECREF(msg);
2668 return 0;
2669 }
2670 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 }
2672 VISIT(c, expr, s->v.Assert.test);
2673 end = compiler_new_block(c);
2674 if (end == NULL)
2675 return 0;
2676 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2677 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2678 if (s->v.Assert.msg) {
2679 VISIT(c, expr, s->v.Assert.msg);
2680 ADDOP_I(c, CALL_FUNCTION, 1);
2681 }
2682 ADDOP_I(c, RAISE_VARARGS, 1);
2683 compiler_use_next_block(c, end);
2684 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685}
2686
2687static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002688compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2689{
2690 if (c->c_interactive && c->c_nestlevel <= 1) {
2691 VISIT(c, expr, value);
2692 ADDOP(c, PRINT_EXPR);
2693 return 1;
2694 }
2695
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002696 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002697 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002698 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002699 }
2700
2701 VISIT(c, expr, value);
2702 ADDOP(c, POP_TOP);
2703 return 1;
2704}
2705
2706static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707compiler_visit_stmt(struct compiler *c, stmt_ty s)
2708{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002709 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 /* Always assign a lineno to the next instruction for a stmt. */
2712 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002713 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 switch (s->kind) {
2717 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002718 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 case ClassDef_kind:
2720 return compiler_class(c, s);
2721 case Return_kind:
2722 if (c->u->u_ste->ste_type != FunctionBlock)
2723 return compiler_error(c, "'return' outside function");
2724 if (s->v.Return.value) {
2725 VISIT(c, expr, s->v.Return.value);
2726 }
2727 else
2728 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2729 ADDOP(c, RETURN_VALUE);
2730 break;
2731 case Delete_kind:
2732 VISIT_SEQ(c, expr, s->v.Delete.targets)
2733 break;
2734 case Assign_kind:
2735 n = asdl_seq_LEN(s->v.Assign.targets);
2736 VISIT(c, expr, s->v.Assign.value);
2737 for (i = 0; i < n; i++) {
2738 if (i < n - 1)
2739 ADDOP(c, DUP_TOP);
2740 VISIT(c, expr,
2741 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2742 }
2743 break;
2744 case AugAssign_kind:
2745 return compiler_augassign(c, s);
2746 case For_kind:
2747 return compiler_for(c, s);
2748 case While_kind:
2749 return compiler_while(c, s);
2750 case If_kind:
2751 return compiler_if(c, s);
2752 case Raise_kind:
2753 n = 0;
2754 if (s->v.Raise.exc) {
2755 VISIT(c, expr, s->v.Raise.exc);
2756 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002757 if (s->v.Raise.cause) {
2758 VISIT(c, expr, s->v.Raise.cause);
2759 n++;
2760 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002762 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002764 case Try_kind:
2765 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 case Assert_kind:
2767 return compiler_assert(c, s);
2768 case Import_kind:
2769 return compiler_import(c, s);
2770 case ImportFrom_kind:
2771 return compiler_from_import(c, s);
2772 case Global_kind:
2773 case Nonlocal_kind:
2774 break;
2775 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002776 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 case Pass_kind:
2778 break;
2779 case Break_kind:
2780 if (!compiler_in_loop(c))
2781 return compiler_error(c, "'break' outside loop");
2782 ADDOP(c, BREAK_LOOP);
2783 break;
2784 case Continue_kind:
2785 return compiler_continue(c);
2786 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002787 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002788 case AsyncFunctionDef_kind:
2789 return compiler_function(c, s, 1);
2790 case AsyncWith_kind:
2791 return compiler_async_with(c, s, 0);
2792 case AsyncFor_kind:
2793 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 }
Yury Selivanov75445082015-05-11 22:57:16 -04002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797}
2798
2799static int
2800unaryop(unaryop_ty op)
2801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 switch (op) {
2803 case Invert:
2804 return UNARY_INVERT;
2805 case Not:
2806 return UNARY_NOT;
2807 case UAdd:
2808 return UNARY_POSITIVE;
2809 case USub:
2810 return UNARY_NEGATIVE;
2811 default:
2812 PyErr_Format(PyExc_SystemError,
2813 "unary op %d should not be possible", op);
2814 return 0;
2815 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816}
2817
2818static int
2819binop(struct compiler *c, operator_ty op)
2820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 switch (op) {
2822 case Add:
2823 return BINARY_ADD;
2824 case Sub:
2825 return BINARY_SUBTRACT;
2826 case Mult:
2827 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002828 case MatMult:
2829 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 case Div:
2831 return BINARY_TRUE_DIVIDE;
2832 case Mod:
2833 return BINARY_MODULO;
2834 case Pow:
2835 return BINARY_POWER;
2836 case LShift:
2837 return BINARY_LSHIFT;
2838 case RShift:
2839 return BINARY_RSHIFT;
2840 case BitOr:
2841 return BINARY_OR;
2842 case BitXor:
2843 return BINARY_XOR;
2844 case BitAnd:
2845 return BINARY_AND;
2846 case FloorDiv:
2847 return BINARY_FLOOR_DIVIDE;
2848 default:
2849 PyErr_Format(PyExc_SystemError,
2850 "binary op %d should not be possible", op);
2851 return 0;
2852 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853}
2854
2855static int
2856cmpop(cmpop_ty op)
2857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 switch (op) {
2859 case Eq:
2860 return PyCmp_EQ;
2861 case NotEq:
2862 return PyCmp_NE;
2863 case Lt:
2864 return PyCmp_LT;
2865 case LtE:
2866 return PyCmp_LE;
2867 case Gt:
2868 return PyCmp_GT;
2869 case GtE:
2870 return PyCmp_GE;
2871 case Is:
2872 return PyCmp_IS;
2873 case IsNot:
2874 return PyCmp_IS_NOT;
2875 case In:
2876 return PyCmp_IN;
2877 case NotIn:
2878 return PyCmp_NOT_IN;
2879 default:
2880 return PyCmp_BAD;
2881 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882}
2883
2884static int
2885inplace_binop(struct compiler *c, operator_ty op)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 switch (op) {
2888 case Add:
2889 return INPLACE_ADD;
2890 case Sub:
2891 return INPLACE_SUBTRACT;
2892 case Mult:
2893 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002894 case MatMult:
2895 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 case Div:
2897 return INPLACE_TRUE_DIVIDE;
2898 case Mod:
2899 return INPLACE_MODULO;
2900 case Pow:
2901 return INPLACE_POWER;
2902 case LShift:
2903 return INPLACE_LSHIFT;
2904 case RShift:
2905 return INPLACE_RSHIFT;
2906 case BitOr:
2907 return INPLACE_OR;
2908 case BitXor:
2909 return INPLACE_XOR;
2910 case BitAnd:
2911 return INPLACE_AND;
2912 case FloorDiv:
2913 return INPLACE_FLOOR_DIVIDE;
2914 default:
2915 PyErr_Format(PyExc_SystemError,
2916 "inplace binary op %d should not be possible", op);
2917 return 0;
2918 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919}
2920
2921static int
2922compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002924 int op, scope;
2925 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 PyObject *dict = c->u->u_names;
2929 PyObject *mangled;
2930 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 mangled = _Py_Mangle(c->u->u_private, name);
2933 if (!mangled)
2934 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002935
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002936 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2937 PyUnicode_CompareWithASCIIString(name, "True") &&
2938 PyUnicode_CompareWithASCIIString(name, "False"));
2939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 op = 0;
2941 optype = OP_NAME;
2942 scope = PyST_GetScope(c->u->u_ste, mangled);
2943 switch (scope) {
2944 case FREE:
2945 dict = c->u->u_freevars;
2946 optype = OP_DEREF;
2947 break;
2948 case CELL:
2949 dict = c->u->u_cellvars;
2950 optype = OP_DEREF;
2951 break;
2952 case LOCAL:
2953 if (c->u->u_ste->ste_type == FunctionBlock)
2954 optype = OP_FAST;
2955 break;
2956 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002957 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 optype = OP_GLOBAL;
2959 break;
2960 case GLOBAL_EXPLICIT:
2961 optype = OP_GLOBAL;
2962 break;
2963 default:
2964 /* scope can be 0 */
2965 break;
2966 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 switch (optype) {
2972 case OP_DEREF:
2973 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002974 case Load:
2975 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2976 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 case Store: op = STORE_DEREF; break;
2978 case AugLoad:
2979 case AugStore:
2980 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002981 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 case Param:
2983 default:
2984 PyErr_SetString(PyExc_SystemError,
2985 "param invalid for deref variable");
2986 return 0;
2987 }
2988 break;
2989 case OP_FAST:
2990 switch (ctx) {
2991 case Load: op = LOAD_FAST; break;
2992 case Store: op = STORE_FAST; break;
2993 case Del: op = DELETE_FAST; break;
2994 case AugLoad:
2995 case AugStore:
2996 break;
2997 case Param:
2998 default:
2999 PyErr_SetString(PyExc_SystemError,
3000 "param invalid for local variable");
3001 return 0;
3002 }
3003 ADDOP_O(c, op, mangled, varnames);
3004 Py_DECREF(mangled);
3005 return 1;
3006 case OP_GLOBAL:
3007 switch (ctx) {
3008 case Load: op = LOAD_GLOBAL; break;
3009 case Store: op = STORE_GLOBAL; break;
3010 case Del: op = DELETE_GLOBAL; break;
3011 case AugLoad:
3012 case AugStore:
3013 break;
3014 case Param:
3015 default:
3016 PyErr_SetString(PyExc_SystemError,
3017 "param invalid for global variable");
3018 return 0;
3019 }
3020 break;
3021 case OP_NAME:
3022 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003023 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 case Store: op = STORE_NAME; break;
3025 case Del: op = DELETE_NAME; break;
3026 case AugLoad:
3027 case AugStore:
3028 break;
3029 case Param:
3030 default:
3031 PyErr_SetString(PyExc_SystemError,
3032 "param invalid for name variable");
3033 return 0;
3034 }
3035 break;
3036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 assert(op);
3039 arg = compiler_add_o(c, dict, mangled);
3040 Py_DECREF(mangled);
3041 if (arg < 0)
3042 return 0;
3043 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044}
3045
3046static int
3047compiler_boolop(struct compiler *c, expr_ty e)
3048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003050 int jumpi;
3051 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 assert(e->kind == BoolOp_kind);
3055 if (e->v.BoolOp.op == And)
3056 jumpi = JUMP_IF_FALSE_OR_POP;
3057 else
3058 jumpi = JUMP_IF_TRUE_OR_POP;
3059 end = compiler_new_block(c);
3060 if (end == NULL)
3061 return 0;
3062 s = e->v.BoolOp.values;
3063 n = asdl_seq_LEN(s) - 1;
3064 assert(n >= 0);
3065 for (i = 0; i < n; ++i) {
3066 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3067 ADDOP_JABS(c, jumpi, end);
3068 }
3069 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3070 compiler_use_next_block(c, end);
3071 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072}
3073
3074static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003075starunpack_helper(struct compiler *c, asdl_seq *elts,
3076 int single_op, int inner_op, int outer_op)
3077{
3078 Py_ssize_t n = asdl_seq_LEN(elts);
3079 Py_ssize_t i, nsubitems = 0, nseen = 0;
3080 for (i = 0; i < n; i++) {
3081 expr_ty elt = asdl_seq_GET(elts, i);
3082 if (elt->kind == Starred_kind) {
3083 if (nseen) {
3084 ADDOP_I(c, inner_op, nseen);
3085 nseen = 0;
3086 nsubitems++;
3087 }
3088 VISIT(c, expr, elt->v.Starred.value);
3089 nsubitems++;
3090 }
3091 else {
3092 VISIT(c, expr, elt);
3093 nseen++;
3094 }
3095 }
3096 if (nsubitems) {
3097 if (nseen) {
3098 ADDOP_I(c, inner_op, nseen);
3099 nsubitems++;
3100 }
3101 ADDOP_I(c, outer_op, nsubitems);
3102 }
3103 else
3104 ADDOP_I(c, single_op, nseen);
3105 return 1;
3106}
3107
3108static int
3109assignment_helper(struct compiler *c, asdl_seq *elts)
3110{
3111 Py_ssize_t n = asdl_seq_LEN(elts);
3112 Py_ssize_t i;
3113 int seen_star = 0;
3114 for (i = 0; i < n; i++) {
3115 expr_ty elt = asdl_seq_GET(elts, i);
3116 if (elt->kind == Starred_kind && !seen_star) {
3117 if ((i >= (1 << 8)) ||
3118 (n-i-1 >= (INT_MAX >> 8)))
3119 return compiler_error(c,
3120 "too many expressions in "
3121 "star-unpacking assignment");
3122 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3123 seen_star = 1;
3124 asdl_seq_SET(elts, i, elt->v.Starred.value);
3125 }
3126 else if (elt->kind == Starred_kind) {
3127 return compiler_error(c,
3128 "two starred expressions in assignment");
3129 }
3130 }
3131 if (!seen_star) {
3132 ADDOP_I(c, UNPACK_SEQUENCE, n);
3133 }
3134 VISIT_SEQ(c, expr, elts);
3135 return 1;
3136}
3137
3138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139compiler_list(struct compiler *c, expr_ty e)
3140{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003141 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003143 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003145 else if (e->v.List.ctx == Load) {
3146 return starunpack_helper(c, elts,
3147 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003149 else
3150 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152}
3153
3154static int
3155compiler_tuple(struct compiler *c, expr_ty e)
3156{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003157 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003159 return assignment_helper(c, elts);
3160 }
3161 else if (e->v.Tuple.ctx == Load) {
3162 return starunpack_helper(c, elts,
3163 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3164 }
3165 else
3166 VISIT_SEQ(c, expr, elts);
3167 return 1;
3168}
3169
3170static int
3171compiler_set(struct compiler *c, expr_ty e)
3172{
3173 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3174 BUILD_SET, BUILD_SET_UNPACK);
3175}
3176
3177static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003178are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3179{
3180 Py_ssize_t i;
3181 for (i = begin; i < end; i++) {
3182 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3183 if (key == NULL || !is_const(key))
3184 return 0;
3185 }
3186 return 1;
3187}
3188
3189static int
3190compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3191{
3192 Py_ssize_t i, n = end - begin;
3193 PyObject *keys, *key;
3194 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3195 for (i = begin; i < end; i++) {
3196 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3197 }
3198 keys = PyTuple_New(n);
3199 if (keys == NULL) {
3200 return 0;
3201 }
3202 for (i = begin; i < end; i++) {
3203 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3204 Py_INCREF(key);
3205 PyTuple_SET_ITEM(keys, i - begin, key);
3206 }
3207 ADDOP_N(c, LOAD_CONST, keys, consts);
3208 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3209 }
3210 else {
3211 for (i = begin; i < end; i++) {
3212 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3213 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3214 }
3215 ADDOP_I(c, BUILD_MAP, n);
3216 }
3217 return 1;
3218}
3219
3220static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003221compiler_dict(struct compiler *c, expr_ty e)
3222{
Victor Stinner976bb402016-03-23 11:36:19 +01003223 Py_ssize_t i, n, elements;
3224 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003225 int is_unpacking = 0;
3226 n = asdl_seq_LEN(e->v.Dict.values);
3227 containers = 0;
3228 elements = 0;
3229 for (i = 0; i < n; i++) {
3230 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3231 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003232 if (!compiler_subdict(c, e, i - elements, i))
3233 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003234 containers++;
3235 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003237 if (is_unpacking) {
3238 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3239 containers++;
3240 }
3241 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003242 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 }
3244 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003245 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003246 if (!compiler_subdict(c, e, n - elements, n))
3247 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003248 containers++;
3249 }
3250 /* If there is more than one dict, they need to be merged into a new
3251 * dict. If there is one dict and it's an unpacking, then it needs
3252 * to be copied into a new dict." */
3253 while (containers > 1 || is_unpacking) {
3254 int oparg = containers < 255 ? containers : 255;
3255 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3256 containers -= (oparg - 1);
3257 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 }
3259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260}
3261
3262static int
3263compiler_compare(struct compiler *c, expr_ty e)
3264{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003265 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3269 VISIT(c, expr, e->v.Compare.left);
3270 n = asdl_seq_LEN(e->v.Compare.ops);
3271 assert(n > 0);
3272 if (n > 1) {
3273 cleanup = compiler_new_block(c);
3274 if (cleanup == NULL)
3275 return 0;
3276 VISIT(c, expr,
3277 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3278 }
3279 for (i = 1; i < n; i++) {
3280 ADDOP(c, DUP_TOP);
3281 ADDOP(c, ROT_THREE);
3282 ADDOP_I(c, COMPARE_OP,
3283 cmpop((cmpop_ty)(asdl_seq_GET(
3284 e->v.Compare.ops, i - 1))));
3285 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3286 NEXT_BLOCK(c);
3287 if (i < (n - 1))
3288 VISIT(c, expr,
3289 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3290 }
3291 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3292 ADDOP_I(c, COMPARE_OP,
3293 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3294 if (n > 1) {
3295 basicblock *end = compiler_new_block(c);
3296 if (end == NULL)
3297 return 0;
3298 ADDOP_JREL(c, JUMP_FORWARD, end);
3299 compiler_use_next_block(c, cleanup);
3300 ADDOP(c, ROT_TWO);
3301 ADDOP(c, POP_TOP);
3302 compiler_use_next_block(c, end);
3303 }
3304 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305}
3306
3307static int
3308compiler_call(struct compiler *c, expr_ty e)
3309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 VISIT(c, expr, e->v.Call.func);
3311 return compiler_call_helper(c, 0,
3312 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003313 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003314}
3315
Eric V. Smith235a6f02015-09-19 14:51:32 -04003316static int
3317compiler_joined_str(struct compiler *c, expr_ty e)
3318{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003319 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003320 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003321 return 1;
3322}
3323
Eric V. Smitha78c7952015-11-03 12:45:05 -05003324/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003325static int
3326compiler_formatted_value(struct compiler *c, expr_ty e)
3327{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003328 /* Our oparg encodes 2 pieces of information: the conversion
3329 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003330
Eric V. Smitha78c7952015-11-03 12:45:05 -05003331 Convert the conversion char to 2 bits:
3332 None: 000 0x0 FVC_NONE
3333 !s : 001 0x1 FVC_STR
3334 !r : 010 0x2 FVC_REPR
3335 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003336
Eric V. Smitha78c7952015-11-03 12:45:05 -05003337 next bit is whether or not we have a format spec:
3338 yes : 100 0x4
3339 no : 000 0x0
3340 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003341
Eric V. Smitha78c7952015-11-03 12:45:05 -05003342 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003343
Eric V. Smitha78c7952015-11-03 12:45:05 -05003344 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003345 VISIT(c, expr, e->v.FormattedValue.value);
3346
Eric V. Smitha78c7952015-11-03 12:45:05 -05003347 switch (e->v.FormattedValue.conversion) {
3348 case 's': oparg = FVC_STR; break;
3349 case 'r': oparg = FVC_REPR; break;
3350 case 'a': oparg = FVC_ASCII; break;
3351 case -1: oparg = FVC_NONE; break;
3352 default:
3353 PyErr_SetString(PyExc_SystemError,
3354 "Unrecognized conversion character");
3355 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003356 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003357 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003358 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003359 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003360 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003361 }
3362
Eric V. Smitha78c7952015-11-03 12:45:05 -05003363 /* And push our opcode and oparg */
3364 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003365 return 1;
3366}
3367
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003368static int
3369compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3370{
3371 Py_ssize_t i, n = end - begin;
3372 keyword_ty kw;
3373 PyObject *keys, *key;
3374 assert(n > 0);
3375 if (n > 1) {
3376 for (i = begin; i < end; i++) {
3377 kw = asdl_seq_GET(keywords, i);
3378 VISIT(c, expr, kw->value);
3379 }
3380 keys = PyTuple_New(n);
3381 if (keys == NULL) {
3382 return 0;
3383 }
3384 for (i = begin; i < end; i++) {
3385 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3386 Py_INCREF(key);
3387 PyTuple_SET_ITEM(keys, i - begin, key);
3388 }
3389 ADDOP_N(c, LOAD_CONST, keys, consts);
3390 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3391 }
3392 else {
3393 /* a for loop only executes once */
3394 for (i = begin; i < end; i++) {
3395 kw = asdl_seq_GET(keywords, i);
3396 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3397 VISIT(c, expr, kw->value);
3398 }
3399 ADDOP_I(c, BUILD_MAP, n);
3400 }
3401 return 1;
3402}
3403
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003404/* shared code between compiler_call and compiler_class */
3405static int
3406compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003407 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003408 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003409 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003412 Py_ssize_t nelts, i, nseen;
3413 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003414
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003415 /* the number of tuples and dictionaries on the stack */
3416 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3417
3418 nkw = 0;
3419 nseen = 0; /* the number of positional arguments on the stack */
3420 nelts = asdl_seq_LEN(args);
3421 for (i = 0; i < nelts; i++) {
3422 expr_ty elt = asdl_seq_GET(args, i);
3423 if (elt->kind == Starred_kind) {
3424 /* A star-arg. If we've seen positional arguments,
3425 pack the positional arguments into a
3426 tuple. */
3427 if (nseen) {
3428 ADDOP_I(c, BUILD_TUPLE, nseen);
3429 nseen = 0;
3430 nsubargs++;
3431 }
3432 VISIT(c, expr, elt->v.Starred.value);
3433 nsubargs++;
3434 }
3435 else if (nsubargs) {
3436 /* We've seen star-args already, so we
3437 count towards items-to-pack-into-tuple. */
3438 VISIT(c, expr, elt);
3439 nseen++;
3440 }
3441 else {
3442 /* Positional arguments before star-arguments
3443 are left on the stack. */
3444 VISIT(c, expr, elt);
3445 n++;
3446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003448 if (nseen) {
3449 /* Pack up any trailing positional arguments. */
3450 ADDOP_I(c, BUILD_TUPLE, nseen);
3451 nsubargs++;
3452 }
3453 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003455 if (nsubargs > 1) {
3456 /* If we ended up with more than one stararg, we need
3457 to concatenate them into a single sequence. */
3458 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3459 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003461
3462 /* Same dance again for keyword arguments */
3463 nseen = 0; /* the number of keyword arguments on the stack following */
3464 nelts = asdl_seq_LEN(keywords);
3465 for (i = 0; i < nelts; i++) {
3466 keyword_ty kw = asdl_seq_GET(keywords, i);
3467 if (kw->arg == NULL) {
3468 /* A keyword argument unpacking. */
3469 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003470 if (nsubkwargs) {
3471 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3472 return 0;
3473 nsubkwargs++;
3474 }
3475 else {
3476 Py_ssize_t j;
3477 for (j = 0; j < nseen; j++) {
3478 VISIT(c, keyword, asdl_seq_GET(keywords, j));
3479 }
3480 nkw = nseen;
3481 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003482 nseen = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003483 }
3484 VISIT(c, expr, kw->value);
3485 nsubkwargs++;
3486 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003487 else {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003488 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003489 }
3490 }
3491 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003492 if (nsubkwargs) {
3493 /* Pack up any trailing keyword arguments. */
3494 if (!compiler_subkwargs(c, keywords, nelts - nseen, nelts))
3495 return 0;
3496 nsubkwargs++;
3497 }
3498 else {
3499 VISIT_SEQ(c, keyword, keywords);
3500 nkw = nseen;
3501 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003502 }
3503 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003505 if (nsubkwargs > 1) {
3506 /* Pack it all up */
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03003507 int function_pos = n + (code & 1) + 2 * nkw + 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003508 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003511 assert(n < 1<<8);
3512 assert(nkw < 1<<24);
3513 n |= nkw << 8;
3514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 switch (code) {
3516 case 0:
3517 ADDOP_I(c, CALL_FUNCTION, n);
3518 break;
3519 case 1:
3520 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3521 break;
3522 case 2:
3523 ADDOP_I(c, CALL_FUNCTION_KW, n);
3524 break;
3525 case 3:
3526 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3527 break;
3528 }
3529 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530}
3531
Nick Coghlan650f0d02007-04-15 12:05:43 +00003532
3533/* List and set comprehensions and generator expressions work by creating a
3534 nested function to perform the actual iteration. This means that the
3535 iteration variables don't leak into the current scope.
3536 The defined function is called immediately following its definition, with the
3537 result of that call being the result of the expression.
3538 The LC/SC version returns the populated container, while the GE version is
3539 flagged in symtable.c as a generator, so it returns the generator object
3540 when the function is called.
3541 This code *knows* that the loop cannot contain break, continue, or return,
3542 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3543
3544 Possible cleanups:
3545 - iterate over the generator sequence instead of using recursion
3546*/
3547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549compiler_comprehension_generator(struct compiler *c,
3550 asdl_seq *generators, int gen_index,
3551 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 /* generate code for the iterator, then each of the ifs,
3554 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 comprehension_ty gen;
3557 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003558 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 start = compiler_new_block(c);
3561 skip = compiler_new_block(c);
3562 if_cleanup = compiler_new_block(c);
3563 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3566 anchor == NULL)
3567 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 if (gen_index == 0) {
3572 /* Receive outermost iter as an implicit argument */
3573 c->u->u_argcount = 1;
3574 ADDOP_I(c, LOAD_FAST, 0);
3575 }
3576 else {
3577 /* Sub-iter - calculate on the fly */
3578 VISIT(c, expr, gen->iter);
3579 ADDOP(c, GET_ITER);
3580 }
3581 compiler_use_next_block(c, start);
3582 ADDOP_JREL(c, FOR_ITER, anchor);
3583 NEXT_BLOCK(c);
3584 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 /* XXX this needs to be cleaned up...a lot! */
3587 n = asdl_seq_LEN(gen->ifs);
3588 for (i = 0; i < n; i++) {
3589 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3590 VISIT(c, expr, e);
3591 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3592 NEXT_BLOCK(c);
3593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 if (++gen_index < asdl_seq_LEN(generators))
3596 if (!compiler_comprehension_generator(c,
3597 generators, gen_index,
3598 elt, val, type))
3599 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 /* only append after the last for generator */
3602 if (gen_index >= asdl_seq_LEN(generators)) {
3603 /* comprehension specific code */
3604 switch (type) {
3605 case COMP_GENEXP:
3606 VISIT(c, expr, elt);
3607 ADDOP(c, YIELD_VALUE);
3608 ADDOP(c, POP_TOP);
3609 break;
3610 case COMP_LISTCOMP:
3611 VISIT(c, expr, elt);
3612 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3613 break;
3614 case COMP_SETCOMP:
3615 VISIT(c, expr, elt);
3616 ADDOP_I(c, SET_ADD, gen_index + 1);
3617 break;
3618 case COMP_DICTCOMP:
3619 /* With 'd[k] = v', v is evaluated before k, so we do
3620 the same. */
3621 VISIT(c, expr, val);
3622 VISIT(c, expr, elt);
3623 ADDOP_I(c, MAP_ADD, gen_index + 1);
3624 break;
3625 default:
3626 return 0;
3627 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 compiler_use_next_block(c, skip);
3630 }
3631 compiler_use_next_block(c, if_cleanup);
3632 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3633 compiler_use_next_block(c, anchor);
3634
3635 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636}
3637
3638static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003639compiler_comprehension(struct compiler *c, expr_ty e, int type,
3640 identifier name, asdl_seq *generators, expr_ty elt,
3641 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 PyCodeObject *co = NULL;
3644 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003645 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 outermost_iter = ((comprehension_ty)
3648 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003649
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003650 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3651 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 if (type != COMP_GENEXP) {
3655 int op;
3656 switch (type) {
3657 case COMP_LISTCOMP:
3658 op = BUILD_LIST;
3659 break;
3660 case COMP_SETCOMP:
3661 op = BUILD_SET;
3662 break;
3663 case COMP_DICTCOMP:
3664 op = BUILD_MAP;
3665 break;
3666 default:
3667 PyErr_Format(PyExc_SystemError,
3668 "unknown comprehension type %d", type);
3669 goto error_in_scope;
3670 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 ADDOP_I(c, op, 0);
3673 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 if (!compiler_comprehension_generator(c, generators, 0, elt,
3676 val, type))
3677 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 if (type != COMP_GENEXP) {
3680 ADDOP(c, RETURN_VALUE);
3681 }
3682
3683 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003684 qualname = c->u->u_qualname;
3685 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003687 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 goto error;
3689
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003690 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003692 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 Py_DECREF(co);
3694
3695 VISIT(c, expr, outermost_iter);
3696 ADDOP(c, GET_ITER);
3697 ADDOP_I(c, CALL_FUNCTION, 1);
3698 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003699error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003701error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003702 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 Py_XDECREF(co);
3704 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003705}
3706
3707static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708compiler_genexp(struct compiler *c, expr_ty e)
3709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 static identifier name;
3711 if (!name) {
3712 name = PyUnicode_FromString("<genexpr>");
3713 if (!name)
3714 return 0;
3715 }
3716 assert(e->kind == GeneratorExp_kind);
3717 return compiler_comprehension(c, e, COMP_GENEXP, name,
3718 e->v.GeneratorExp.generators,
3719 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720}
3721
3722static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003723compiler_listcomp(struct compiler *c, expr_ty e)
3724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 static identifier name;
3726 if (!name) {
3727 name = PyUnicode_FromString("<listcomp>");
3728 if (!name)
3729 return 0;
3730 }
3731 assert(e->kind == ListComp_kind);
3732 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3733 e->v.ListComp.generators,
3734 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003735}
3736
3737static int
3738compiler_setcomp(struct compiler *c, expr_ty e)
3739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 static identifier name;
3741 if (!name) {
3742 name = PyUnicode_FromString("<setcomp>");
3743 if (!name)
3744 return 0;
3745 }
3746 assert(e->kind == SetComp_kind);
3747 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3748 e->v.SetComp.generators,
3749 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003750}
3751
3752
3753static int
3754compiler_dictcomp(struct compiler *c, expr_ty e)
3755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 static identifier name;
3757 if (!name) {
3758 name = PyUnicode_FromString("<dictcomp>");
3759 if (!name)
3760 return 0;
3761 }
3762 assert(e->kind == DictComp_kind);
3763 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3764 e->v.DictComp.generators,
3765 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003766}
3767
3768
3769static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770compiler_visit_keyword(struct compiler *c, keyword_ty k)
3771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3773 VISIT(c, expr, k->value);
3774 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775}
3776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 whether they are true or false.
3779
3780 Return values: 1 for true, 0 for false, -1 for non-constant.
3781 */
3782
3783static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003784expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 char *id;
3787 switch (e->kind) {
3788 case Ellipsis_kind:
3789 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003790 case Constant_kind:
3791 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 case Num_kind:
3793 return PyObject_IsTrue(e->v.Num.n);
3794 case Str_kind:
3795 return PyObject_IsTrue(e->v.Str.s);
3796 case Name_kind:
3797 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003799 if (id && strcmp(id, "__debug__") == 0)
3800 return !c->c_optimize;
3801 return -1;
3802 case NameConstant_kind: {
3803 PyObject *o = e->v.NameConstant.value;
3804 if (o == Py_None)
3805 return 0;
3806 else if (o == Py_True)
3807 return 1;
3808 else if (o == Py_False)
3809 return 0;
3810 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 default:
3812 return -1;
3813 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814}
3815
Yury Selivanov75445082015-05-11 22:57:16 -04003816
3817/*
3818 Implements the async with statement.
3819
3820 The semantics outlined in that PEP are as follows:
3821
3822 async with EXPR as VAR:
3823 BLOCK
3824
3825 It is implemented roughly as:
3826
3827 context = EXPR
3828 exit = context.__aexit__ # not calling it
3829 value = await context.__aenter__()
3830 try:
3831 VAR = value # if VAR present in the syntax
3832 BLOCK
3833 finally:
3834 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003835 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003836 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003837 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003838 if not (await exit(*exc)):
3839 raise
3840 */
3841static int
3842compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3843{
3844 basicblock *block, *finally;
3845 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3846
3847 assert(s->kind == AsyncWith_kind);
3848
3849 block = compiler_new_block(c);
3850 finally = compiler_new_block(c);
3851 if (!block || !finally)
3852 return 0;
3853
3854 /* Evaluate EXPR */
3855 VISIT(c, expr, item->context_expr);
3856
3857 ADDOP(c, BEFORE_ASYNC_WITH);
3858 ADDOP(c, GET_AWAITABLE);
3859 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3860 ADDOP(c, YIELD_FROM);
3861
3862 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3863
3864 /* SETUP_ASYNC_WITH pushes a finally block. */
3865 compiler_use_next_block(c, block);
3866 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3867 return 0;
3868 }
3869
3870 if (item->optional_vars) {
3871 VISIT(c, expr, item->optional_vars);
3872 }
3873 else {
3874 /* Discard result from context.__aenter__() */
3875 ADDOP(c, POP_TOP);
3876 }
3877
3878 pos++;
3879 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3880 /* BLOCK code */
3881 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3882 else if (!compiler_async_with(c, s, pos))
3883 return 0;
3884
3885 /* End of try block; start the finally block */
3886 ADDOP(c, POP_BLOCK);
3887 compiler_pop_fblock(c, FINALLY_TRY, block);
3888
3889 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3890 compiler_use_next_block(c, finally);
3891 if (!compiler_push_fblock(c, FINALLY_END, finally))
3892 return 0;
3893
3894 /* Finally block starts; context.__exit__ is on the stack under
3895 the exception or return information. Just issue our magic
3896 opcode. */
3897 ADDOP(c, WITH_CLEANUP_START);
3898
3899 ADDOP(c, GET_AWAITABLE);
3900 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3901 ADDOP(c, YIELD_FROM);
3902
3903 ADDOP(c, WITH_CLEANUP_FINISH);
3904
3905 /* Finally block ends. */
3906 ADDOP(c, END_FINALLY);
3907 compiler_pop_fblock(c, FINALLY_END, finally);
3908 return 1;
3909}
3910
3911
Guido van Rossumc2e20742006-02-27 22:32:47 +00003912/*
3913 Implements the with statement from PEP 343.
3914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003916
3917 with EXPR as VAR:
3918 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919
Guido van Rossumc2e20742006-02-27 22:32:47 +00003920 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921
Thomas Wouters477c8d52006-05-27 19:21:47 +00003922 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003923 exit = context.__exit__ # not calling it
3924 value = context.__enter__()
3925 try:
3926 VAR = value # if VAR present in the syntax
3927 BLOCK
3928 finally:
3929 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003930 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003931 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003932 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003933 exit(*exc)
3934 */
3935static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003936compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003937{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003938 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003939 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003940
3941 assert(s->kind == With_kind);
3942
Guido van Rossumc2e20742006-02-27 22:32:47 +00003943 block = compiler_new_block(c);
3944 finally = compiler_new_block(c);
3945 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003946 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003947
Thomas Wouters477c8d52006-05-27 19:21:47 +00003948 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003949 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003950 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003951
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003952 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003953 compiler_use_next_block(c, block);
3954 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003955 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003956 }
3957
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003958 if (item->optional_vars) {
3959 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003960 }
3961 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003963 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003964 }
3965
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003966 pos++;
3967 if (pos == asdl_seq_LEN(s->v.With.items))
3968 /* BLOCK code */
3969 VISIT_SEQ(c, stmt, s->v.With.body)
3970 else if (!compiler_with(c, s, pos))
3971 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003972
3973 /* End of try block; start the finally block */
3974 ADDOP(c, POP_BLOCK);
3975 compiler_pop_fblock(c, FINALLY_TRY, block);
3976
3977 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3978 compiler_use_next_block(c, finally);
3979 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003980 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003981
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003982 /* Finally block starts; context.__exit__ is on the stack under
3983 the exception or return information. Just issue our magic
3984 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003985 ADDOP(c, WITH_CLEANUP_START);
3986 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003987
3988 /* Finally block ends. */
3989 ADDOP(c, END_FINALLY);
3990 compiler_pop_fblock(c, FINALLY_END, finally);
3991 return 1;
3992}
3993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994static int
3995compiler_visit_expr(struct compiler *c, expr_ty e)
3996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 /* If expr e has a different line number than the last expr/stmt,
3998 set a new line number for the next instruction.
3999 */
4000 if (e->lineno > c->u->u_lineno) {
4001 c->u->u_lineno = e->lineno;
4002 c->u->u_lineno_set = 0;
4003 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004004 /* Updating the column offset is always harmless. */
4005 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 switch (e->kind) {
4007 case BoolOp_kind:
4008 return compiler_boolop(c, e);
4009 case BinOp_kind:
4010 VISIT(c, expr, e->v.BinOp.left);
4011 VISIT(c, expr, e->v.BinOp.right);
4012 ADDOP(c, binop(c, e->v.BinOp.op));
4013 break;
4014 case UnaryOp_kind:
4015 VISIT(c, expr, e->v.UnaryOp.operand);
4016 ADDOP(c, unaryop(e->v.UnaryOp.op));
4017 break;
4018 case Lambda_kind:
4019 return compiler_lambda(c, e);
4020 case IfExp_kind:
4021 return compiler_ifexp(c, e);
4022 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004023 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004025 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 case GeneratorExp_kind:
4027 return compiler_genexp(c, e);
4028 case ListComp_kind:
4029 return compiler_listcomp(c, e);
4030 case SetComp_kind:
4031 return compiler_setcomp(c, e);
4032 case DictComp_kind:
4033 return compiler_dictcomp(c, e);
4034 case Yield_kind:
4035 if (c->u->u_ste->ste_type != FunctionBlock)
4036 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004037 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4038 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004039 if (e->v.Yield.value) {
4040 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 }
4042 else {
4043 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4044 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004045 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004047 case YieldFrom_kind:
4048 if (c->u->u_ste->ste_type != FunctionBlock)
4049 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004050
4051 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4052 return compiler_error(c, "'yield from' inside async function");
4053
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004054 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004055 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004056 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4057 ADDOP(c, YIELD_FROM);
4058 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004059 case Await_kind:
4060 if (c->u->u_ste->ste_type != FunctionBlock)
4061 return compiler_error(c, "'await' outside function");
4062
Yury Selivanov9dec0352015-06-30 12:49:04 -04004063 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
4064 return compiler_error(
4065 c, "'await' expressions in comprehensions are not supported");
4066
Yury Selivanov75445082015-05-11 22:57:16 -04004067 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
4068 return compiler_error(c, "'await' outside async function");
4069
4070 VISIT(c, expr, e->v.Await.value);
4071 ADDOP(c, GET_AWAITABLE);
4072 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4073 ADDOP(c, YIELD_FROM);
4074 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 case Compare_kind:
4076 return compiler_compare(c, e);
4077 case Call_kind:
4078 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004079 case Constant_kind:
4080 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4081 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 case Num_kind:
4083 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4084 break;
4085 case Str_kind:
4086 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4087 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004088 case JoinedStr_kind:
4089 return compiler_joined_str(c, e);
4090 case FormattedValue_kind:
4091 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 case Bytes_kind:
4093 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4094 break;
4095 case Ellipsis_kind:
4096 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4097 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004098 case NameConstant_kind:
4099 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4100 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 /* The following exprs can be assignment targets. */
4102 case Attribute_kind:
4103 if (e->v.Attribute.ctx != AugStore)
4104 VISIT(c, expr, e->v.Attribute.value);
4105 switch (e->v.Attribute.ctx) {
4106 case AugLoad:
4107 ADDOP(c, DUP_TOP);
4108 /* Fall through to load */
4109 case Load:
4110 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4111 break;
4112 case AugStore:
4113 ADDOP(c, ROT_TWO);
4114 /* Fall through to save */
4115 case Store:
4116 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4117 break;
4118 case Del:
4119 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4120 break;
4121 case Param:
4122 default:
4123 PyErr_SetString(PyExc_SystemError,
4124 "param invalid in attribute expression");
4125 return 0;
4126 }
4127 break;
4128 case Subscript_kind:
4129 switch (e->v.Subscript.ctx) {
4130 case AugLoad:
4131 VISIT(c, expr, e->v.Subscript.value);
4132 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4133 break;
4134 case Load:
4135 VISIT(c, expr, e->v.Subscript.value);
4136 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4137 break;
4138 case AugStore:
4139 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4140 break;
4141 case Store:
4142 VISIT(c, expr, e->v.Subscript.value);
4143 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4144 break;
4145 case Del:
4146 VISIT(c, expr, e->v.Subscript.value);
4147 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4148 break;
4149 case Param:
4150 default:
4151 PyErr_SetString(PyExc_SystemError,
4152 "param invalid in subscript expression");
4153 return 0;
4154 }
4155 break;
4156 case Starred_kind:
4157 switch (e->v.Starred.ctx) {
4158 case Store:
4159 /* In all legitimate cases, the Starred node was already replaced
4160 * by compiler_list/compiler_tuple. XXX: is that okay? */
4161 return compiler_error(c,
4162 "starred assignment target must be in a list or tuple");
4163 default:
4164 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004165 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 }
4167 break;
4168 case Name_kind:
4169 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4170 /* child nodes of List and Tuple will have expr_context set */
4171 case List_kind:
4172 return compiler_list(c, e);
4173 case Tuple_kind:
4174 return compiler_tuple(c, e);
4175 }
4176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177}
4178
4179static int
4180compiler_augassign(struct compiler *c, stmt_ty s)
4181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 expr_ty e = s->v.AugAssign.target;
4183 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 switch (e->kind) {
4188 case Attribute_kind:
4189 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4190 AugLoad, e->lineno, e->col_offset, c->c_arena);
4191 if (auge == NULL)
4192 return 0;
4193 VISIT(c, expr, auge);
4194 VISIT(c, expr, s->v.AugAssign.value);
4195 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4196 auge->v.Attribute.ctx = AugStore;
4197 VISIT(c, expr, auge);
4198 break;
4199 case Subscript_kind:
4200 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4201 AugLoad, e->lineno, e->col_offset, c->c_arena);
4202 if (auge == NULL)
4203 return 0;
4204 VISIT(c, expr, auge);
4205 VISIT(c, expr, s->v.AugAssign.value);
4206 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4207 auge->v.Subscript.ctx = AugStore;
4208 VISIT(c, expr, auge);
4209 break;
4210 case Name_kind:
4211 if (!compiler_nameop(c, e->v.Name.id, Load))
4212 return 0;
4213 VISIT(c, expr, s->v.AugAssign.value);
4214 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4215 return compiler_nameop(c, e->v.Name.id, Store);
4216 default:
4217 PyErr_Format(PyExc_SystemError,
4218 "invalid node type (%d) for augmented assignment",
4219 e->kind);
4220 return 0;
4221 }
4222 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004223}
4224
4225static int
4226compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 struct fblockinfo *f;
4229 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004230 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 "too many statically nested blocks");
4232 return 0;
4233 }
4234 f = &c->u->u_fblock[c->u->u_nfblocks++];
4235 f->fb_type = t;
4236 f->fb_block = b;
4237 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004238}
4239
4240static void
4241compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 struct compiler_unit *u = c->u;
4244 assert(u->u_nfblocks > 0);
4245 u->u_nfblocks--;
4246 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4247 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004248}
4249
Thomas Wouters89f507f2006-12-13 04:49:30 +00004250static int
4251compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 int i;
4253 struct compiler_unit *u = c->u;
4254 for (i = 0; i < u->u_nfblocks; ++i) {
4255 if (u->u_fblock[i].fb_type == LOOP)
4256 return 1;
4257 }
4258 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004259}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260/* Raises a SyntaxError and returns 0.
4261 If something goes wrong, a different exception may be raised.
4262*/
4263
4264static int
4265compiler_error(struct compiler *c, const char *errstr)
4266{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004267 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269
Victor Stinner14e461d2013-08-26 22:28:21 +02004270 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 if (!loc) {
4272 Py_INCREF(Py_None);
4273 loc = Py_None;
4274 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004275 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004276 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 if (!u)
4278 goto exit;
4279 v = Py_BuildValue("(zO)", errstr, u);
4280 if (!v)
4281 goto exit;
4282 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 Py_DECREF(loc);
4285 Py_XDECREF(u);
4286 Py_XDECREF(v);
4287 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004288}
4289
4290static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291compiler_handle_subscr(struct compiler *c, const char *kind,
4292 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 /* XXX this code is duplicated */
4297 switch (ctx) {
4298 case AugLoad: /* fall through to Load */
4299 case Load: op = BINARY_SUBSCR; break;
4300 case AugStore:/* fall through to Store */
4301 case Store: op = STORE_SUBSCR; break;
4302 case Del: op = DELETE_SUBSCR; break;
4303 case Param:
4304 PyErr_Format(PyExc_SystemError,
4305 "invalid %s kind %d in subscript\n",
4306 kind, ctx);
4307 return 0;
4308 }
4309 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004310 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 }
4312 else if (ctx == AugStore) {
4313 ADDOP(c, ROT_THREE);
4314 }
4315 ADDOP(c, op);
4316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317}
4318
4319static int
4320compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 int n = 2;
4323 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 /* only handles the cases where BUILD_SLICE is emitted */
4326 if (s->v.Slice.lower) {
4327 VISIT(c, expr, s->v.Slice.lower);
4328 }
4329 else {
4330 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4331 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 if (s->v.Slice.upper) {
4334 VISIT(c, expr, s->v.Slice.upper);
4335 }
4336 else {
4337 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4338 }
4339
4340 if (s->v.Slice.step) {
4341 n++;
4342 VISIT(c, expr, s->v.Slice.step);
4343 }
4344 ADDOP_I(c, BUILD_SLICE, n);
4345 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346}
4347
4348static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4350 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 switch (s->kind) {
4353 case Slice_kind:
4354 return compiler_slice(c, s, ctx);
4355 case Index_kind:
4356 VISIT(c, expr, s->v.Index.value);
4357 break;
4358 case ExtSlice_kind:
4359 default:
4360 PyErr_SetString(PyExc_SystemError,
4361 "extended slice invalid in nested slice");
4362 return 0;
4363 }
4364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365}
4366
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004367static int
4368compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 char * kindname = NULL;
4371 switch (s->kind) {
4372 case Index_kind:
4373 kindname = "index";
4374 if (ctx != AugStore) {
4375 VISIT(c, expr, s->v.Index.value);
4376 }
4377 break;
4378 case Slice_kind:
4379 kindname = "slice";
4380 if (ctx != AugStore) {
4381 if (!compiler_slice(c, s, ctx))
4382 return 0;
4383 }
4384 break;
4385 case ExtSlice_kind:
4386 kindname = "extended slice";
4387 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004388 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 for (i = 0; i < n; i++) {
4390 slice_ty sub = (slice_ty)asdl_seq_GET(
4391 s->v.ExtSlice.dims, i);
4392 if (!compiler_visit_nested_slice(c, sub, ctx))
4393 return 0;
4394 }
4395 ADDOP_I(c, BUILD_TUPLE, n);
4396 }
4397 break;
4398 default:
4399 PyErr_Format(PyExc_SystemError,
4400 "invalid subscript kind %d", s->kind);
4401 return 0;
4402 }
4403 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404}
4405
Thomas Wouters89f507f2006-12-13 04:49:30 +00004406/* End of the compiler section, beginning of the assembler section */
4407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408/* do depth-first search of basic block graph, starting with block.
4409 post records the block indices in post-order.
4410
4411 XXX must handle implicit jumps from one block to next
4412*/
4413
Thomas Wouters89f507f2006-12-13 04:49:30 +00004414struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 PyObject *a_bytecode; /* string containing bytecode */
4416 int a_offset; /* offset into bytecode */
4417 int a_nblocks; /* number of reachable blocks */
4418 basicblock **a_postorder; /* list of blocks in dfs postorder */
4419 PyObject *a_lnotab; /* string containing lnotab */
4420 int a_lnotab_off; /* offset into lnotab */
4421 int a_lineno; /* last lineno of emitted instruction */
4422 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004423};
4424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425static void
4426dfs(struct compiler *c, basicblock *b, struct assembler *a)
4427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 int i;
4429 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 if (b->b_seen)
4432 return;
4433 b->b_seen = 1;
4434 if (b->b_next != NULL)
4435 dfs(c, b->b_next, a);
4436 for (i = 0; i < b->b_iused; i++) {
4437 instr = &b->b_instr[i];
4438 if (instr->i_jrel || instr->i_jabs)
4439 dfs(c, instr->i_target, a);
4440 }
4441 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442}
4443
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004444static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004445stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4446{
Larry Hastings3a907972013-11-23 14:49:22 -08004447 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 struct instr *instr;
4449 if (b->b_seen || b->b_startdepth >= depth)
4450 return maxdepth;
4451 b->b_seen = 1;
4452 b->b_startdepth = depth;
4453 for (i = 0; i < b->b_iused; i++) {
4454 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004455 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4456 if (effect == PY_INVALID_STACK_EFFECT) {
4457 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4458 Py_FatalError("PyCompile_OpcodeStackEffect()");
4459 }
4460 depth += effect;
4461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 if (depth > maxdepth)
4463 maxdepth = depth;
4464 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4465 if (instr->i_jrel || instr->i_jabs) {
4466 target_depth = depth;
4467 if (instr->i_opcode == FOR_ITER) {
4468 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004469 }
4470 else if (instr->i_opcode == SETUP_FINALLY ||
4471 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 target_depth = depth+3;
4473 if (target_depth > maxdepth)
4474 maxdepth = target_depth;
4475 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004476 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4477 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4478 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 maxdepth = stackdepth_walk(c, instr->i_target,
4480 target_depth, maxdepth);
4481 if (instr->i_opcode == JUMP_ABSOLUTE ||
4482 instr->i_opcode == JUMP_FORWARD) {
4483 goto out; /* remaining code is dead */
4484 }
4485 }
4486 }
4487 if (b->b_next)
4488 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004489out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 b->b_seen = 0;
4491 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004492}
4493
4494/* Find the flow path that needs the largest stack. We assume that
4495 * cycles in the flow graph have no net effect on the stack depth.
4496 */
4497static int
4498stackdepth(struct compiler *c)
4499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 basicblock *b, *entryblock;
4501 entryblock = NULL;
4502 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4503 b->b_seen = 0;
4504 b->b_startdepth = INT_MIN;
4505 entryblock = b;
4506 }
4507 if (!entryblock)
4508 return 0;
4509 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004510}
4511
4512static int
4513assemble_init(struct assembler *a, int nblocks, int firstlineno)
4514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 memset(a, 0, sizeof(struct assembler));
4516 a->a_lineno = firstlineno;
4517 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4518 if (!a->a_bytecode)
4519 return 0;
4520 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4521 if (!a->a_lnotab)
4522 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004523 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 PyErr_NoMemory();
4525 return 0;
4526 }
4527 a->a_postorder = (basicblock **)PyObject_Malloc(
4528 sizeof(basicblock *) * nblocks);
4529 if (!a->a_postorder) {
4530 PyErr_NoMemory();
4531 return 0;
4532 }
4533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004534}
4535
4536static void
4537assemble_free(struct assembler *a)
4538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 Py_XDECREF(a->a_bytecode);
4540 Py_XDECREF(a->a_lnotab);
4541 if (a->a_postorder)
4542 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004543}
4544
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004545static int
4546blocksize(basicblock *b)
4547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 int i;
4549 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004552 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004554}
4555
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004556/* Appends a pair to the end of the line number table, a_lnotab, representing
4557 the instruction's bytecode offset and line number. See
4558 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004559
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004560static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004561assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004564 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 d_bytecode = a->a_offset - a->a_lineno_off;
4568 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 if(d_bytecode == 0 && d_lineno == 0)
4573 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 if (d_bytecode > 255) {
4576 int j, nbytes, ncodes = d_bytecode / 255;
4577 nbytes = a->a_lnotab_off + 2 * ncodes;
4578 len = PyBytes_GET_SIZE(a->a_lnotab);
4579 if (nbytes >= len) {
4580 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4581 len = nbytes;
4582 else if (len <= INT_MAX / 2)
4583 len *= 2;
4584 else {
4585 PyErr_NoMemory();
4586 return 0;
4587 }
4588 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4589 return 0;
4590 }
4591 lnotab = (unsigned char *)
4592 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4593 for (j = 0; j < ncodes; j++) {
4594 *lnotab++ = 255;
4595 *lnotab++ = 0;
4596 }
4597 d_bytecode -= ncodes * 255;
4598 a->a_lnotab_off += ncodes * 2;
4599 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004600 assert(0 <= d_bytecode && d_bytecode <= 255);
4601
4602 if (d_lineno < -128 || 127 < d_lineno) {
4603 int j, nbytes, ncodes, k;
4604 if (d_lineno < 0) {
4605 k = -128;
4606 /* use division on positive numbers */
4607 ncodes = (-d_lineno) / 128;
4608 }
4609 else {
4610 k = 127;
4611 ncodes = d_lineno / 127;
4612 }
4613 d_lineno -= ncodes * k;
4614 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 nbytes = a->a_lnotab_off + 2 * ncodes;
4616 len = PyBytes_GET_SIZE(a->a_lnotab);
4617 if (nbytes >= len) {
4618 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4619 len = nbytes;
4620 else if (len <= INT_MAX / 2)
4621 len *= 2;
4622 else {
4623 PyErr_NoMemory();
4624 return 0;
4625 }
4626 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4627 return 0;
4628 }
4629 lnotab = (unsigned char *)
4630 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4631 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004632 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 d_bytecode = 0;
4634 for (j = 1; j < ncodes; j++) {
4635 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004636 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 a->a_lnotab_off += ncodes * 2;
4639 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004640 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 len = PyBytes_GET_SIZE(a->a_lnotab);
4643 if (a->a_lnotab_off + 2 >= len) {
4644 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4645 return 0;
4646 }
4647 lnotab = (unsigned char *)
4648 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 a->a_lnotab_off += 2;
4651 if (d_bytecode) {
4652 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004653 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 }
4655 else { /* First line of a block; def stmt, etc. */
4656 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004657 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 }
4659 a->a_lineno = i->i_lineno;
4660 a->a_lineno_off = a->a_offset;
4661 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004662}
4663
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004664/* assemble_emit()
4665 Extend the bytecode with a new instruction.
4666 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004667*/
4668
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004669static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004670assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004671{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004672 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4674 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004675
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004676 arg = i->i_oparg;
4677 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 if (i->i_lineno && !assemble_lnotab(a, i))
4679 return 0;
4680 if (a->a_offset + size >= len) {
4681 if (len > PY_SSIZE_T_MAX / 2)
4682 return 0;
4683 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4684 return 0;
4685 }
4686 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4687 a->a_offset += size;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004688 write_op_arg((unsigned char*)code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004690}
4691
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004692static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004693assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004696 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 /* Compute the size of each block and fixup jump args.
4700 Replace block pointer with position in bytecode. */
4701 do {
4702 totsize = 0;
4703 for (i = a->a_nblocks - 1; i >= 0; i--) {
4704 b = a->a_postorder[i];
4705 bsize = blocksize(b);
4706 b->b_offset = totsize;
4707 totsize += bsize;
4708 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004709 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4711 bsize = b->b_offset;
4712 for (i = 0; i < b->b_iused; i++) {
4713 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004714 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 /* Relative jumps are computed relative to
4716 the instruction pointer after fetching
4717 the jump instruction.
4718 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004719 bsize += isize;
4720 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004722 if (instr->i_jrel) {
4723 instr->i_oparg -= bsize;
4724 }
4725 if (instrsize(instr->i_oparg) != isize) {
4726 extended_arg_recompile = 1;
4727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 }
4730 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 /* XXX: This is an awful hack that could hurt performance, but
4733 on the bright side it should work until we come up
4734 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 The issue is that in the first loop blocksize() is called
4737 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004738 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 So we loop until we stop seeing new EXTENDED_ARGs.
4742 The only EXTENDED_ARGs that could be popping up are
4743 ones in jump instructions. So this should converge
4744 fairly quickly.
4745 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004746 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004747}
4748
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004749static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004750dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 PyObject *tuple, *k, *v;
4753 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 tuple = PyTuple_New(size);
4756 if (tuple == NULL)
4757 return NULL;
4758 while (PyDict_Next(dict, &pos, &k, &v)) {
4759 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004760 /* The keys of the dictionary are tuples. (see compiler_add_o
4761 * and _PyCode_ConstantKey). The object we want is always second,
4762 * though. */
4763 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 Py_INCREF(k);
4765 assert((i - offset) < size);
4766 assert((i - offset) >= 0);
4767 PyTuple_SET_ITEM(tuple, i - offset, k);
4768 }
4769 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004770}
4771
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004772static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004776 int flags = 0;
4777 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004779 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 if (ste->ste_nested)
4781 flags |= CO_NESTED;
4782 if (ste->ste_generator)
4783 flags |= CO_GENERATOR;
4784 if (ste->ste_varargs)
4785 flags |= CO_VARARGS;
4786 if (ste->ste_varkeywords)
4787 flags |= CO_VARKEYWORDS;
4788 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 /* (Only) inherit compilerflags in PyCF_MASK */
4791 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 n = PyDict_Size(c->u->u_freevars);
4794 if (n < 0)
4795 return -1;
4796 if (n == 0) {
4797 n = PyDict_Size(c->u->u_cellvars);
4798 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004799 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004801 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 }
4803 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004806}
4807
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004808static PyCodeObject *
4809makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 PyObject *tmp;
4812 PyCodeObject *co = NULL;
4813 PyObject *consts = NULL;
4814 PyObject *names = NULL;
4815 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 PyObject *name = NULL;
4817 PyObject *freevars = NULL;
4818 PyObject *cellvars = NULL;
4819 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004820 Py_ssize_t nlocals;
4821 int nlocals_int;
4822 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004823 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 tmp = dict_keys_inorder(c->u->u_consts, 0);
4826 if (!tmp)
4827 goto error;
4828 consts = PySequence_List(tmp); /* optimize_code requires a list */
4829 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 names = dict_keys_inorder(c->u->u_names, 0);
4832 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4833 if (!consts || !names || !varnames)
4834 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4837 if (!cellvars)
4838 goto error;
4839 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4840 if (!freevars)
4841 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004843 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004844 assert(nlocals < INT_MAX);
4845 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 flags = compute_code_flags(c);
4848 if (flags < 0)
4849 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4852 if (!bytecode)
4853 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4856 if (!tmp)
4857 goto error;
4858 Py_DECREF(consts);
4859 consts = tmp;
4860
Victor Stinnerf8e32212013-11-19 23:56:34 +01004861 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4862 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4863 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004864 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 bytecode, consts, names, varnames,
4866 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004867 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 c->u->u_firstlineno,
4869 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004870 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 Py_XDECREF(consts);
4872 Py_XDECREF(names);
4873 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 Py_XDECREF(name);
4875 Py_XDECREF(freevars);
4876 Py_XDECREF(cellvars);
4877 Py_XDECREF(bytecode);
4878 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004879}
4880
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004881
4882/* For debugging purposes only */
4883#if 0
4884static void
4885dump_instr(const struct instr *i)
4886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 const char *jrel = i->i_jrel ? "jrel " : "";
4888 const char *jabs = i->i_jabs ? "jabs " : "";
4889 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004892 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4896 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004897}
4898
4899static void
4900dump_basicblock(const basicblock *b)
4901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004902 const char *seen = b->b_seen ? "seen " : "";
4903 const char *b_return = b->b_return ? "return " : "";
4904 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4905 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4906 if (b->b_instr) {
4907 int i;
4908 for (i = 0; i < b->b_iused; i++) {
4909 fprintf(stderr, " [%02d] ", i);
4910 dump_instr(b->b_instr + i);
4911 }
4912 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004913}
4914#endif
4915
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004916static PyCodeObject *
4917assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 basicblock *b, *entryblock;
4920 struct assembler a;
4921 int i, j, nblocks;
4922 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 /* Make sure every block that falls off the end returns None.
4925 XXX NEXT_BLOCK() isn't quite right, because if the last
4926 block ends with a jump or return b_next shouldn't set.
4927 */
4928 if (!c->u->u_curblock->b_return) {
4929 NEXT_BLOCK(c);
4930 if (addNone)
4931 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4932 ADDOP(c, RETURN_VALUE);
4933 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 nblocks = 0;
4936 entryblock = NULL;
4937 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4938 nblocks++;
4939 entryblock = b;
4940 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 /* Set firstlineno if it wasn't explicitly set. */
4943 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04004944 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4946 else
4947 c->u->u_firstlineno = 1;
4948 }
4949 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4950 goto error;
4951 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 /* Can't modify the bytecode after computing jump offsets. */
4954 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 /* Emit code in reverse postorder from dfs. */
4957 for (i = a.a_nblocks - 1; i >= 0; i--) {
4958 b = a.a_postorder[i];
4959 for (j = 0; j < b->b_iused; j++)
4960 if (!assemble_emit(&a, &b->b_instr[j]))
4961 goto error;
4962 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4965 goto error;
4966 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4967 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004970 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 assemble_free(&a);
4972 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004973}
Georg Brandl8334fd92010-12-04 10:26:46 +00004974
4975#undef PyAST_Compile
4976PyAPI_FUNC(PyCodeObject *)
4977PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4978 PyArena *arena)
4979{
4980 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4981}