blob: efb6c7ee3e22f6e5ef8284aa144ae863e4523ce9 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
182static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184
185static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189/* Returns true if there is a loop on the fblock stack. */
190static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
192static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000193static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500195static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400196static int compiler_async_with(struct compiler *, stmt_ty, int);
197static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400200 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500201static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400202static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400207#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100389 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100395 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100417dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100451 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100458 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinner976bb402016-03-23 11:36:19 +0100479 assert((Py_uintptr_t)block != 0xcbcbcbcbU);
480 assert((Py_uintptr_t)block != 0xfbfbfbfbU);
481 assert((Py_uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100525 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000551 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100562 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100623
624 block = compiler_new_block(c);
625 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400629 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
630 if (!compiler_set_qualname(c))
631 return 0;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635}
636
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000637static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638compiler_exit_scope(struct compiler *c)
639{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100640 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 c->c_nestlevel--;
644 compiler_unit_free(c->u);
645 /* Restore c->u to the parent unit. */
646 n = PyList_GET_SIZE(c->c_stack) - 1;
647 if (n >= 0) {
648 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400649 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 assert(c->u);
651 /* we are deleting from a list so this really shouldn't fail */
652 if (PySequence_DelItem(c->c_stack, n) < 0)
653 Py_FatalError("compiler_exit_scope()");
654 compiler_unit_check(c->u);
655 }
656 else
657 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659}
660
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400661static int
662compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100663{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 _Py_static_string(dot_locals, ".<locals>");
666 Py_ssize_t stack_size;
667 struct compiler_unit *u = c->u;
668 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400672 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 if (stack_size > 1) {
674 int scope, force_global = 0;
675 struct compiler_unit *parent;
676 PyObject *mangled, *capsule;
677
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400678 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400679 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(parent);
681
Yury Selivanov75445082015-05-11 22:57:16 -0400682 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
683 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
684 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(u->u_name);
686 mangled = _Py_Mangle(parent->u_private, u->u_name);
687 if (!mangled)
688 return 0;
689 scope = PyST_GetScope(parent->u_ste, mangled);
690 Py_DECREF(mangled);
691 assert(scope != GLOBAL_IMPLICIT);
692 if (scope == GLOBAL_EXPLICIT)
693 force_global = 1;
694 }
695
696 if (!force_global) {
697 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400698 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
700 dot_locals_str = _PyUnicode_FromId(&dot_locals);
701 if (dot_locals_str == NULL)
702 return 0;
703 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
704 if (base == NULL)
705 return 0;
706 }
707 else {
708 Py_INCREF(parent->u_qualname);
709 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100711 }
712 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 if (base != NULL) {
715 dot_str = _PyUnicode_FromId(&dot);
716 if (dot_str == NULL) {
717 Py_DECREF(base);
718 return 0;
719 }
720 name = PyUnicode_Concat(base, dot_str);
721 Py_DECREF(base);
722 if (name == NULL)
723 return 0;
724 PyUnicode_Append(&name, u->u_name);
725 if (name == NULL)
726 return 0;
727 }
728 else {
729 Py_INCREF(u->u_name);
730 name = u->u_name;
731 }
732 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100733
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100735}
736
Eric V. Smith235a6f02015-09-19 14:51:32 -0400737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000738/* Allocate a new block and return a pointer to it.
739 Returns NULL on error.
740*/
741
742static basicblock *
743compiler_new_block(struct compiler *c)
744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 basicblock *b;
746 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 u = c->u;
749 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
750 if (b == NULL) {
751 PyErr_NoMemory();
752 return NULL;
753 }
754 memset((void *)b, 0, sizeof(basicblock));
755 /* Extend the singly linked list of blocks with new block. */
756 b->b_list = u->u_blocks;
757 u->u_blocks = b;
758 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759}
760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762compiler_next_block(struct compiler *c)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 basicblock *block = compiler_new_block(c);
765 if (block == NULL)
766 return NULL;
767 c->u->u_curblock->b_next = block;
768 c->u->u_curblock = block;
769 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
772static basicblock *
773compiler_use_next_block(struct compiler *c, basicblock *block)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 assert(block != NULL);
776 c->u->u_curblock->b_next = block;
777 c->u->u_curblock = block;
778 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
781/* Returns the offset of the next instruction in the current block's
782 b_instr array. Resizes the b_instr as necessary.
783 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000784*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786static int
787compiler_next_instr(struct compiler *c, basicblock *b)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(b != NULL);
790 if (b->b_instr == NULL) {
791 b->b_instr = (struct instr *)PyObject_Malloc(
792 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
793 if (b->b_instr == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 b->b_ialloc = DEFAULT_BLOCK_SIZE;
798 memset((char *)b->b_instr, 0,
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 }
801 else if (b->b_iused == b->b_ialloc) {
802 struct instr *tmp;
803 size_t oldsize, newsize;
804 oldsize = b->b_ialloc * sizeof(struct instr);
805 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (oldsize > (PY_SIZE_MAX >> 1)) {
808 PyErr_NoMemory();
809 return -1;
810 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (newsize == 0) {
813 PyErr_NoMemory();
814 return -1;
815 }
816 b->b_ialloc <<= 1;
817 tmp = (struct instr *)PyObject_Realloc(
818 (void *)b->b_instr, newsize);
819 if (tmp == NULL) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_instr = tmp;
824 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
825 }
826 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827}
828
Christian Heimes2202f872008-02-06 14:31:34 +0000829/* Set the i_lineno member of the instruction at offset off if the
830 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 already been set. If it has been set, the call has no effect.
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833 The line number is reset in the following cases:
834 - when entering a new scope
835 - on each statement
836 - on each expression that start a new line
837 - before the "except" clause
838 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841static void
842compiler_set_lineno(struct compiler *c, int off)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 basicblock *b;
845 if (c->u->u_lineno_set)
846 return;
847 c->u->u_lineno_set = 1;
848 b = c->u->u_curblock;
849 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850}
851
Larry Hastings3a907972013-11-23 14:49:22 -0800852int
853PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 switch (opcode) {
856 case POP_TOP:
857 return -1;
858 case ROT_TWO:
859 case ROT_THREE:
860 return 0;
861 case DUP_TOP:
862 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000863 case DUP_TOP_TWO:
864 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 case UNARY_POSITIVE:
867 case UNARY_NEGATIVE:
868 case UNARY_NOT:
869 case UNARY_INVERT:
870 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case SET_ADD:
873 case LIST_APPEND:
874 return -1;
875 case MAP_ADD:
876 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case BINARY_POWER:
879 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400880 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case BINARY_MODULO:
882 case BINARY_ADD:
883 case BINARY_SUBTRACT:
884 case BINARY_SUBSCR:
885 case BINARY_FLOOR_DIVIDE:
886 case BINARY_TRUE_DIVIDE:
887 return -1;
888 case INPLACE_FLOOR_DIVIDE:
889 case INPLACE_TRUE_DIVIDE:
890 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case INPLACE_ADD:
893 case INPLACE_SUBTRACT:
894 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400895 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_MODULO:
897 return -1;
898 case STORE_SUBSCR:
899 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case DELETE_SUBSCR:
901 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_LSHIFT:
904 case BINARY_RSHIFT:
905 case BINARY_AND:
906 case BINARY_XOR:
907 case BINARY_OR:
908 return -1;
909 case INPLACE_POWER:
910 return -1;
911 case GET_ITER:
912 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case PRINT_EXPR:
915 return -1;
916 case LOAD_BUILD_CLASS:
917 return 1;
918 case INPLACE_LSHIFT:
919 case INPLACE_RSHIFT:
920 case INPLACE_AND:
921 case INPLACE_XOR:
922 case INPLACE_OR:
923 return -1;
924 case BREAK_LOOP:
925 return 0;
926 case SETUP_WITH:
927 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400928 case WITH_CLEANUP_START:
929 return 1;
930 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case RETURN_VALUE:
933 return -1;
934 case IMPORT_STAR:
935 return -1;
936 case YIELD_VALUE:
937 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500938 case YIELD_FROM:
939 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case POP_BLOCK:
941 return 0;
942 case POP_EXCEPT:
943 return 0; /* -3 except if bad bytecode */
944 case END_FINALLY:
945 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case STORE_NAME:
948 return -1;
949 case DELETE_NAME:
950 return 0;
951 case UNPACK_SEQUENCE:
952 return oparg-1;
953 case UNPACK_EX:
954 return (oparg&0xFF) + (oparg>>8);
955 case FOR_ITER:
956 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case STORE_ATTR:
959 return -2;
960 case DELETE_ATTR:
961 return -1;
962 case STORE_GLOBAL:
963 return -1;
964 case DELETE_GLOBAL:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case LOAD_CONST:
967 return 1;
968 case LOAD_NAME:
969 return 1;
970 case BUILD_TUPLE:
971 case BUILD_LIST:
972 case BUILD_SET:
973 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400974 case BUILD_LIST_UNPACK:
975 case BUILD_TUPLE_UNPACK:
976 case BUILD_SET_UNPACK:
977 case BUILD_MAP_UNPACK:
978 return 1 - oparg;
979 case BUILD_MAP_UNPACK_WITH_CALL:
980 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700982 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300983 case BUILD_CONST_KEY_MAP:
984 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 case LOAD_ATTR:
986 return 0;
987 case COMPARE_OP:
988 return -1;
989 case IMPORT_NAME:
990 return -1;
991 case IMPORT_FROM:
992 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 case JUMP_FORWARD:
995 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
996 case JUMP_IF_FALSE_OR_POP: /* "" */
997 case JUMP_ABSOLUTE:
998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case POP_JUMP_IF_FALSE:
1001 case POP_JUMP_IF_TRUE:
1002 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case LOAD_GLOBAL:
1005 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case CONTINUE_LOOP:
1008 return 0;
1009 case SETUP_LOOP:
1010 return 0;
1011 case SETUP_EXCEPT:
1012 case SETUP_FINALLY:
1013 return 6; /* can push 3 values for the new exception
1014 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case LOAD_FAST:
1017 return 1;
1018 case STORE_FAST:
1019 return -1;
1020 case DELETE_FAST:
1021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case RAISE_VARARGS:
1024 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001025#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 case CALL_FUNCTION:
1027 return -NARGS(oparg);
1028 case CALL_FUNCTION_VAR:
1029 case CALL_FUNCTION_KW:
1030 return -NARGS(oparg)-1;
1031 case CALL_FUNCTION_VAR_KW:
1032 return -NARGS(oparg)-2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001033#undef NARGS
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001034 case MAKE_FUNCTION:
1035 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1036 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case BUILD_SLICE:
1038 if (oparg == 3)
1039 return -2;
1040 else
1041 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_CLOSURE:
1044 return 1;
1045 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001046 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return 1;
1048 case STORE_DEREF:
1049 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001050 case DELETE_DEREF:
1051 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001052 case GET_AWAITABLE:
1053 return 0;
1054 case SETUP_ASYNC_WITH:
1055 return 6;
1056 case BEFORE_ASYNC_WITH:
1057 return 1;
1058 case GET_AITER:
1059 return 0;
1060 case GET_ANEXT:
1061 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001062 case GET_YIELD_FROM_ITER:
1063 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001064 case FORMAT_VALUE:
1065 /* If there's a fmt_spec on the stack, we go from 2->1,
1066 else 1->1. */
1067 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001069 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
Larry Hastings3a907972013-11-23 14:49:22 -08001071 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001072}
1073
1074/* Add an opcode with no argument.
1075 Returns 0 on failure, 1 on success.
1076*/
1077
1078static int
1079compiler_addop(struct compiler *c, int opcode)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 basicblock *b;
1082 struct instr *i;
1083 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001084 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 off = compiler_next_instr(c, c->u->u_curblock);
1086 if (off < 0)
1087 return 0;
1088 b = c->u->u_curblock;
1089 i = &b->b_instr[off];
1090 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001091 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (opcode == RETURN_VALUE)
1093 b->b_return = 1;
1094 compiler_set_lineno(c, off);
1095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096}
1097
Victor Stinnerf8e32212013-11-19 23:56:34 +01001098static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *t, *v;
1102 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Victor Stinnerefb24132016-01-22 12:33:12 +01001104 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (t == NULL)
1106 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 v = PyDict_GetItem(dict, t);
1109 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001110 if (PyErr_Occurred()) {
1111 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001115 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!v) {
1117 Py_DECREF(t);
1118 return -1;
1119 }
1120 if (PyDict_SetItem(dict, t, v) < 0) {
1121 Py_DECREF(t);
1122 Py_DECREF(v);
1123 return -1;
1124 }
1125 Py_DECREF(v);
1126 }
1127 else
1128 arg = PyLong_AsLong(v);
1129 Py_DECREF(t);
1130 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131}
1132
1133static int
1134compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001137 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return compiler_addop_i(c, opcode, arg);
1141}
1142
1143static int
1144compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1149 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001150 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 arg = compiler_add_o(c, dict, mangled);
1152 Py_DECREF(mangled);
1153 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return compiler_addop_i(c, opcode, arg);
1156}
1157
1158/* Add an opcode with an integer argument.
1159 Returns 0 on failure, 1 on success.
1160*/
1161
1162static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001163compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 struct instr *i;
1166 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001167
Victor Stinner2ad474b2016-03-01 23:34:47 +01001168 /* oparg value is unsigned, but a signed C int is usually used to store
1169 it in the C code (like Python/ceval.c).
1170
1171 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1172
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001173 The argument of a concrete bytecode instruction is limited to 8-bit.
1174 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1175 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001176 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 off = compiler_next_instr(c, c->u->u_curblock);
1179 if (off < 0)
1180 return 0;
1181 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001182 i->i_opcode = opcode;
1183 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 compiler_set_lineno(c, off);
1185 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188static int
1189compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct instr *i;
1192 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001194 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 assert(b != NULL);
1196 off = compiler_next_instr(c, c->u->u_curblock);
1197 if (off < 0)
1198 return 0;
1199 i = &c->u->u_curblock->b_instr[off];
1200 i->i_opcode = opcode;
1201 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (absolute)
1203 i->i_jabs = 1;
1204 else
1205 i->i_jrel = 1;
1206 compiler_set_lineno(c, off);
1207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208}
1209
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001210/* NEXT_BLOCK() creates an implicit jump from the current block
1211 to the new block.
1212
1213 The returns inside this macro make it impossible to decref objects
1214 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (compiler_next_block((C)) == NULL) \
1218 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219}
1220
1221#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (!compiler_addop((C), (OP))) \
1223 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224}
1225
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001226#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (!compiler_addop((C), (OP))) { \
1228 compiler_exit_scope(c); \
1229 return 0; \
1230 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001231}
1232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001238/* Same as ADDOP_O, but steals a reference. */
1239#define ADDOP_N(C, OP, O, TYPE) { \
1240 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1241 Py_DECREF((O)); \
1242 return 0; \
1243 } \
1244 Py_DECREF((O)); \
1245}
1246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1249 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (!compiler_addop_i((C), (OP), (O))) \
1254 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_j((C), (OP), (O), 1)) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_j((C), (OP), (O), 0)) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1268 the ASDL name to synthesize the name of the C type and the visit function.
1269*/
1270
1271#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!compiler_visit_ ## TYPE((C), (V))) \
1273 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001276#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_visit_ ## TYPE((C), (V))) { \
1278 compiler_exit_scope(c); \
1279 return 0; \
1280 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001281}
1282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_visit_slice((C), (V), (CTX))) \
1285 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286}
1287
1288#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 int _i; \
1290 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1291 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1292 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1293 if (!compiler_visit_ ## TYPE((C), elt)) \
1294 return 0; \
1295 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001298#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 int _i; \
1300 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1301 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1302 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1303 if (!compiler_visit_ ## TYPE((C), elt)) { \
1304 compiler_exit_scope(c); \
1305 return 0; \
1306 } \
1307 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308}
1309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310static int
1311compiler_isdocstring(stmt_ty s)
1312{
1313 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001314 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001315 if (s->v.Expr.value->kind == Str_kind)
1316 return 1;
1317 if (s->v.Expr.value->kind == Constant_kind)
1318 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1319 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001322static int
1323is_const(expr_ty e)
1324{
1325 switch (e->kind) {
1326 case Constant_kind:
1327 case Num_kind:
1328 case Str_kind:
1329 case Bytes_kind:
1330 case Ellipsis_kind:
1331 case NameConstant_kind:
1332 return 1;
1333 default:
1334 return 0;
1335 }
1336}
1337
1338static PyObject *
1339get_const_value(expr_ty e)
1340{
1341 switch (e->kind) {
1342 case Constant_kind:
1343 return e->v.Constant.value;
1344 case Num_kind:
1345 return e->v.Num.n;
1346 case Str_kind:
1347 return e->v.Str.s;
1348 case Bytes_kind:
1349 return e->v.Bytes.s;
1350 case Ellipsis_kind:
1351 return Py_Ellipsis;
1352 case NameConstant_kind:
1353 return e->v.NameConstant.value;
1354 default:
1355 assert(!is_const(e));
1356 return NULL;
1357 }
1358}
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360/* Compile a sequence of statements, checking for a docstring. */
1361
1362static int
1363compiler_body(struct compiler *c, asdl_seq *stmts)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 int i = 0;
1366 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!asdl_seq_LEN(stmts))
1369 return 1;
1370 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001371 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* don't generate docstrings if -OO */
1373 i = 1;
1374 VISIT(c, expr, st->v.Expr.value);
1375 if (!compiler_nameop(c, __doc__, Store))
1376 return 0;
1377 }
1378 for (; i < asdl_seq_LEN(stmts); i++)
1379 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1380 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381}
1382
1383static PyCodeObject *
1384compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyCodeObject *co;
1387 int addNone = 1;
1388 static PyObject *module;
1389 if (!module) {
1390 module = PyUnicode_InternFromString("<module>");
1391 if (!module)
1392 return NULL;
1393 }
1394 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001395 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 return NULL;
1397 switch (mod->kind) {
1398 case Module_kind:
1399 if (!compiler_body(c, mod->v.Module.body)) {
1400 compiler_exit_scope(c);
1401 return 0;
1402 }
1403 break;
1404 case Interactive_kind:
1405 c->c_interactive = 1;
1406 VISIT_SEQ_IN_SCOPE(c, stmt,
1407 mod->v.Interactive.body);
1408 break;
1409 case Expression_kind:
1410 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1411 addNone = 0;
1412 break;
1413 case Suite_kind:
1414 PyErr_SetString(PyExc_SystemError,
1415 "suite should not be possible");
1416 return 0;
1417 default:
1418 PyErr_Format(PyExc_SystemError,
1419 "module kind %d should not be possible",
1420 mod->kind);
1421 return 0;
1422 }
1423 co = assemble(c, addNone);
1424 compiler_exit_scope(c);
1425 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001426}
1427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428/* The test for LOCAL must come before the test for FREE in order to
1429 handle classes where name is both local and free. The local var is
1430 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001431*/
1432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433static int
1434get_ref_type(struct compiler *c, PyObject *name)
1435{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001436 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001437 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1438 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1439 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001440 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (scope == 0) {
1442 char buf[350];
1443 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001444 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001446 PyUnicode_AsUTF8(name),
1447 PyUnicode_AsUTF8(c->u->u_name),
1448 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1449 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1450 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1451 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 );
1453 Py_FatalError(buf);
1454 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457}
1458
1459static int
1460compiler_lookup_arg(PyObject *dict, PyObject *name)
1461{
1462 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001463 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001465 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001467 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001469 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001470 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
1473static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001474compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001476 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001477 if (qualname == NULL)
1478 qualname = co->co_name;
1479
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001480 if (free) {
1481 for (i = 0; i < free; ++i) {
1482 /* Bypass com_addop_varname because it will generate
1483 LOAD_DEREF but LOAD_CLOSURE is needed.
1484 */
1485 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1486 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001488 /* Special case: If a class contains a method with a
1489 free variable that has the same name as a method,
1490 the name will be considered free *and* local in the
1491 class. It should be handled by the closure, as
1492 well as by the normal name loookup logic.
1493 */
1494 reftype = get_ref_type(c, name);
1495 if (reftype == CELL)
1496 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1497 else /* (reftype == FREE) */
1498 arg = compiler_lookup_arg(c->u->u_freevars, name);
1499 if (arg == -1) {
1500 fprintf(stderr,
1501 "lookup %s in %s %d %d\n"
1502 "freevars of %s: %s\n",
1503 PyUnicode_AsUTF8(PyObject_Repr(name)),
1504 PyUnicode_AsUTF8(c->u->u_name),
1505 reftype, arg,
1506 PyUnicode_AsUTF8(co->co_name),
1507 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1508 Py_FatalError("compiler_make_closure()");
1509 }
1510 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001512 flags |= 0x08;
1513 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001516 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001517 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
1521static int
1522compiler_decorators(struct compiler *c, asdl_seq* decos)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!decos)
1527 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1530 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1531 }
1532 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001535static Py_ssize_t
Guido van Rossum4f72a782006-10-27 23:31:49 +00001536compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001538{
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001539 int i;
1540 PyObject *keys = NULL;
1541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1543 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1544 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1545 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001546 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001547 if (!mangled) {
1548 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001550 if (keys == NULL) {
1551 keys = PyList_New(1);
1552 if (keys == NULL) {
1553 Py_DECREF(mangled);
1554 return -1;
1555 }
1556 PyList_SET_ITEM(keys, 0, mangled);
1557 }
1558 else {
1559 int res = PyList_Append(keys, mangled);
1560 Py_DECREF(mangled);
1561 if (res == -1) {
1562 goto error;
1563 }
1564 }
1565 if (!compiler_visit_expr(c, default_)) {
1566 goto error;
1567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
1569 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001570 if (keys != NULL) {
1571 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1572 PyObject *keys_tuple = PyList_AsTuple(keys);
1573 Py_DECREF(keys);
1574 if (keys_tuple == NULL) {
1575 return -1;
1576 }
1577 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1578 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
1579 return default_count;
1580 }
1581 else {
1582 return 0;
1583 }
1584
1585error:
1586 Py_XDECREF(keys);
1587 return -1;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001588}
1589
1590static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001591compiler_visit_argannotation(struct compiler *c, identifier id,
1592 expr_ty annotation, PyObject *names)
1593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001595 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001597 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001598 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001599 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001600 if (PyList_Append(names, mangled) < 0) {
1601 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001602 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001603 }
1604 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001606 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001607}
1608
1609static int
1610compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1611 PyObject *names)
1612{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001613 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 for (i = 0; i < asdl_seq_LEN(args); i++) {
1615 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001616 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 c,
1618 arg->arg,
1619 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001620 names))
1621 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001623 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001624}
1625
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001626static Py_ssize_t
Neal Norwitzc1505362006-12-28 06:47:50 +00001627compiler_visit_annotations(struct compiler *c, arguments_ty args,
1628 expr_ty returns)
1629{
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001630 /* Push arg annotation dict. Return # of items pushed.
1631 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001632
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001633 Returns -1 on error.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 */
1635 static identifier return_str;
1636 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001637 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 names = PyList_New(0);
1639 if (!names)
1640 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001641
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001642 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001644 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001645 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001646 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001648 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001650 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001651 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001652 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (!return_str) {
1656 return_str = PyUnicode_InternFromString("return");
1657 if (!return_str)
1658 goto error;
1659 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001660 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 goto error;
1662 }
1663
1664 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001666 PyObject *keytuple = PyList_AsTuple(names);
1667 Py_DECREF(names);
1668 if (keytuple == NULL) {
1669 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001671 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1672 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001674 else {
1675 Py_DECREF(names);
1676 }
1677 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001678
1679error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_DECREF(names);
1681 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001682}
1683
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001684static Py_ssize_t
1685compiler_default_arguments(struct compiler *c, arguments_ty args)
1686{
1687 Py_ssize_t funcflags = 0;
1688 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
1689 VISIT_SEQ(c, expr, args->defaults);
1690 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1691 funcflags |= 0x01;
1692 }
1693 if (args->kwonlyargs) {
1694 Py_ssize_t res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1695 args->kw_defaults);
1696 if (res < 0) {
1697 return -1;
1698 }
1699 else if (res > 0) {
1700 funcflags |= 0x02;
1701 }
1702 }
1703 return funcflags;
1704}
1705
Neal Norwitzc1505362006-12-28 06:47:50 +00001706static int
Yury Selivanov75445082015-05-11 22:57:16 -04001707compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001710 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001711 arguments_ty args;
1712 expr_ty returns;
1713 identifier name;
1714 asdl_seq* decos;
1715 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001717 Py_ssize_t i, n, funcflags;
1718 int docstring;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001720 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721
Yury Selivanov75445082015-05-11 22:57:16 -04001722 if (is_async) {
1723 assert(s->kind == AsyncFunctionDef_kind);
1724
1725 args = s->v.AsyncFunctionDef.args;
1726 returns = s->v.AsyncFunctionDef.returns;
1727 decos = s->v.AsyncFunctionDef.decorator_list;
1728 name = s->v.AsyncFunctionDef.name;
1729 body = s->v.AsyncFunctionDef.body;
1730
1731 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1732 } else {
1733 assert(s->kind == FunctionDef_kind);
1734
1735 args = s->v.FunctionDef.args;
1736 returns = s->v.FunctionDef.returns;
1737 decos = s->v.FunctionDef.decorator_list;
1738 name = s->v.FunctionDef.name;
1739 body = s->v.FunctionDef.body;
1740
1741 scope_type = COMPILER_SCOPE_FUNCTION;
1742 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (!compiler_decorators(c, decos))
1745 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001746
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001747 funcflags = compiler_default_arguments(c, args);
1748 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001750 }
1751
1752 num_annotations = compiler_visit_annotations(c, args, returns);
1753 if (num_annotations < 0) {
1754 return 0;
1755 }
1756 else if (num_annotations > 0) {
1757 funcflags |= 0x04;
1758 }
1759
1760 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1761 return 0;
1762 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763
Yury Selivanov75445082015-05-11 22:57:16 -04001764 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001766 if (docstring && c->c_optimize < 2) {
1767 if (st->v.Expr.value->kind == Constant_kind)
1768 first_const = st->v.Expr.value->v.Constant.value;
1769 else
1770 first_const = st->v.Expr.value->v.Str.s;
1771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1773 compiler_exit_scope(c);
1774 return 0;
1775 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 c->u->u_argcount = asdl_seq_LEN(args->args);
1778 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001779 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* if there was a docstring, we need to skip the first statement */
1781 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001782 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 VISIT_IN_SCOPE(c, stmt, st);
1784 }
1785 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001786 qualname = c->u->u_qualname;
1787 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001789 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001790 Py_XDECREF(qualname);
1791 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794
Yury Selivanovb7666a32015-07-22 14:48:57 +03001795 if (is_async)
1796 co->co_flags |= CO_COROUTINE;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001797 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001798 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* decorators */
1802 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1803 ADDOP_I(c, CALL_FUNCTION, 1);
1804 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805
Yury Selivanov75445082015-05-11 22:57:16 -04001806 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807}
1808
1809static int
1810compiler_class(struct compiler *c, stmt_ty s)
1811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PyCodeObject *co;
1813 PyObject *str;
1814 int i;
1815 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (!compiler_decorators(c, decos))
1818 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 /* ultimately generate code for:
1821 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1822 where:
1823 <func> is a function/closure created from the class body;
1824 it has a single argument (__locals__) where the dict
1825 (or MutableSequence) representing the locals is passed
1826 <name> is the class name
1827 <bases> is the positional arguments and *varargs argument
1828 <keywords> is the keyword arguments and **kwds argument
1829 This borrows from compiler_call.
1830 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001833 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1834 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return 0;
1836 /* this block represents what we do in the new scope */
1837 {
1838 /* use the class name for name mangling */
1839 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001840 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 /* load (global) __name__ ... */
1842 str = PyUnicode_InternFromString("__name__");
1843 if (!str || !compiler_nameop(c, str, Load)) {
1844 Py_XDECREF(str);
1845 compiler_exit_scope(c);
1846 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 Py_DECREF(str);
1849 /* ... and store it as __module__ */
1850 str = PyUnicode_InternFromString("__module__");
1851 if (!str || !compiler_nameop(c, str, Store)) {
1852 Py_XDECREF(str);
1853 compiler_exit_scope(c);
1854 return 0;
1855 }
1856 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001857 assert(c->u->u_qualname);
1858 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001859 str = PyUnicode_InternFromString("__qualname__");
1860 if (!str || !compiler_nameop(c, str, Store)) {
1861 Py_XDECREF(str);
1862 compiler_exit_scope(c);
1863 return 0;
1864 }
1865 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* compile the body proper */
1867 if (!compiler_body(c, s->v.ClassDef.body)) {
1868 compiler_exit_scope(c);
1869 return 0;
1870 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001871 if (c->u->u_ste->ste_needs_class_closure) {
1872 /* return the (empty) __class__ cell */
1873 str = PyUnicode_InternFromString("__class__");
1874 if (str == NULL) {
1875 compiler_exit_scope(c);
1876 return 0;
1877 }
1878 i = compiler_lookup_arg(c->u->u_cellvars, str);
1879 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001880 if (i < 0) {
1881 compiler_exit_scope(c);
1882 return 0;
1883 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001884 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* Return the cell where to store __class__ */
1886 ADDOP_I(c, LOAD_CLOSURE, i);
1887 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001888 else {
1889 assert(PyDict_Size(c->u->u_cellvars) == 0);
1890 /* This happens when nobody references the cell. Return None. */
1891 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1894 /* create the code object */
1895 co = assemble(c, 1);
1896 }
1897 /* leave the new scope */
1898 compiler_exit_scope(c);
1899 if (co == NULL)
1900 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* 2. load the 'build_class' function */
1903 ADDOP(c, LOAD_BUILD_CLASS);
1904
1905 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001906 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Py_DECREF(co);
1908
1909 /* 4. load class name */
1910 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1911
1912 /* 5. generate the rest of the code for the call */
1913 if (!compiler_call_helper(c, 2,
1914 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001915 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return 0;
1917
1918 /* 6. apply decorators */
1919 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1920 ADDOP_I(c, CALL_FUNCTION, 1);
1921 }
1922
1923 /* 7. store into <name> */
1924 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1925 return 0;
1926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927}
1928
1929static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001930compiler_ifexp(struct compiler *c, expr_ty e)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 basicblock *end, *next;
1933
1934 assert(e->kind == IfExp_kind);
1935 end = compiler_new_block(c);
1936 if (end == NULL)
1937 return 0;
1938 next = compiler_new_block(c);
1939 if (next == NULL)
1940 return 0;
1941 VISIT(c, expr, e->v.IfExp.test);
1942 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1943 VISIT(c, expr, e->v.IfExp.body);
1944 ADDOP_JREL(c, JUMP_FORWARD, end);
1945 compiler_use_next_block(c, next);
1946 VISIT(c, expr, e->v.IfExp.orelse);
1947 compiler_use_next_block(c, end);
1948 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001949}
1950
1951static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952compiler_lambda(struct compiler *c, expr_ty e)
1953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001955 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001957 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 arguments_ty args = e->v.Lambda.args;
1959 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (!name) {
1962 name = PyUnicode_InternFromString("<lambda>");
1963 if (!name)
1964 return 0;
1965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001967 funcflags = compiler_default_arguments(c, args);
1968 if (funcflags == -1) {
1969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001971
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001972 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001973 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* Make None the first constant, so the lambda can't have a
1977 docstring. */
1978 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 c->u->u_argcount = asdl_seq_LEN(args->args);
1982 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1983 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1984 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001985 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
1987 else {
1988 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001989 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001991 qualname = c->u->u_qualname;
1992 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001994 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001997 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001998 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Py_DECREF(co);
2000
2001 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002}
2003
2004static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005compiler_if(struct compiler *c, stmt_ty s)
2006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 basicblock *end, *next;
2008 int constant;
2009 assert(s->kind == If_kind);
2010 end = compiler_new_block(c);
2011 if (end == NULL)
2012 return 0;
2013
Georg Brandl8334fd92010-12-04 10:26:46 +00002014 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* constant = 0: "if 0"
2016 * constant = 1: "if 1", "if 2", ...
2017 * constant = -1: rest */
2018 if (constant == 0) {
2019 if (s->v.If.orelse)
2020 VISIT_SEQ(c, stmt, s->v.If.orelse);
2021 } else if (constant == 1) {
2022 VISIT_SEQ(c, stmt, s->v.If.body);
2023 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002024 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 next = compiler_new_block(c);
2026 if (next == NULL)
2027 return 0;
2028 }
2029 else
2030 next = end;
2031 VISIT(c, expr, s->v.If.test);
2032 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2033 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002034 if (asdl_seq_LEN(s->v.If.orelse)) {
2035 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 compiler_use_next_block(c, next);
2037 VISIT_SEQ(c, stmt, s->v.If.orelse);
2038 }
2039 }
2040 compiler_use_next_block(c, end);
2041 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042}
2043
2044static int
2045compiler_for(struct compiler *c, stmt_ty s)
2046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 start = compiler_new_block(c);
2050 cleanup = compiler_new_block(c);
2051 end = compiler_new_block(c);
2052 if (start == NULL || end == NULL || cleanup == NULL)
2053 return 0;
2054 ADDOP_JREL(c, SETUP_LOOP, end);
2055 if (!compiler_push_fblock(c, LOOP, start))
2056 return 0;
2057 VISIT(c, expr, s->v.For.iter);
2058 ADDOP(c, GET_ITER);
2059 compiler_use_next_block(c, start);
2060 ADDOP_JREL(c, FOR_ITER, cleanup);
2061 VISIT(c, expr, s->v.For.target);
2062 VISIT_SEQ(c, stmt, s->v.For.body);
2063 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2064 compiler_use_next_block(c, cleanup);
2065 ADDOP(c, POP_BLOCK);
2066 compiler_pop_fblock(c, LOOP, start);
2067 VISIT_SEQ(c, stmt, s->v.For.orelse);
2068 compiler_use_next_block(c, end);
2069 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070}
2071
Yury Selivanov75445082015-05-11 22:57:16 -04002072
2073static int
2074compiler_async_for(struct compiler *c, stmt_ty s)
2075{
2076 static PyObject *stopiter_error = NULL;
2077 basicblock *try, *except, *end, *after_try, *try_cleanup,
2078 *after_loop, *after_loop_else;
2079
2080 if (stopiter_error == NULL) {
2081 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2082 if (stopiter_error == NULL)
2083 return 0;
2084 }
2085
2086 try = compiler_new_block(c);
2087 except = compiler_new_block(c);
2088 end = compiler_new_block(c);
2089 after_try = compiler_new_block(c);
2090 try_cleanup = compiler_new_block(c);
2091 after_loop = compiler_new_block(c);
2092 after_loop_else = compiler_new_block(c);
2093
2094 if (try == NULL || except == NULL || end == NULL
2095 || after_try == NULL || try_cleanup == NULL)
2096 return 0;
2097
2098 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2099 if (!compiler_push_fblock(c, LOOP, try))
2100 return 0;
2101
2102 VISIT(c, expr, s->v.AsyncFor.iter);
2103 ADDOP(c, GET_AITER);
2104 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2105 ADDOP(c, YIELD_FROM);
2106
2107 compiler_use_next_block(c, try);
2108
2109
2110 ADDOP_JREL(c, SETUP_EXCEPT, except);
2111 if (!compiler_push_fblock(c, EXCEPT, try))
2112 return 0;
2113
2114 ADDOP(c, GET_ANEXT);
2115 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2116 ADDOP(c, YIELD_FROM);
2117 VISIT(c, expr, s->v.AsyncFor.target);
2118 ADDOP(c, POP_BLOCK);
2119 compiler_pop_fblock(c, EXCEPT, try);
2120 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2121
2122
2123 compiler_use_next_block(c, except);
2124 ADDOP(c, DUP_TOP);
2125 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2126 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2127 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2128
2129 ADDOP(c, POP_TOP);
2130 ADDOP(c, POP_TOP);
2131 ADDOP(c, POP_TOP);
2132 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2133 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2134 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2135
2136
2137 compiler_use_next_block(c, try_cleanup);
2138 ADDOP(c, END_FINALLY);
2139
2140 compiler_use_next_block(c, after_try);
2141 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2142 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2143
2144 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2145 compiler_pop_fblock(c, LOOP, try);
2146
2147 compiler_use_next_block(c, after_loop);
2148 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2149
2150 compiler_use_next_block(c, after_loop_else);
2151 VISIT_SEQ(c, stmt, s->v.For.orelse);
2152
2153 compiler_use_next_block(c, end);
2154
2155 return 1;
2156}
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158static int
2159compiler_while(struct compiler *c, stmt_ty s)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002162 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (constant == 0) {
2165 if (s->v.While.orelse)
2166 VISIT_SEQ(c, stmt, s->v.While.orelse);
2167 return 1;
2168 }
2169 loop = compiler_new_block(c);
2170 end = compiler_new_block(c);
2171 if (constant == -1) {
2172 anchor = compiler_new_block(c);
2173 if (anchor == NULL)
2174 return 0;
2175 }
2176 if (loop == NULL || end == NULL)
2177 return 0;
2178 if (s->v.While.orelse) {
2179 orelse = compiler_new_block(c);
2180 if (orelse == NULL)
2181 return 0;
2182 }
2183 else
2184 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 ADDOP_JREL(c, SETUP_LOOP, end);
2187 compiler_use_next_block(c, loop);
2188 if (!compiler_push_fblock(c, LOOP, loop))
2189 return 0;
2190 if (constant == -1) {
2191 VISIT(c, expr, s->v.While.test);
2192 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2193 }
2194 VISIT_SEQ(c, stmt, s->v.While.body);
2195 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* XXX should the two POP instructions be in a separate block
2198 if there is no else clause ?
2199 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002201 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002203 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 compiler_pop_fblock(c, LOOP, loop);
2205 if (orelse != NULL) /* what if orelse is just pass? */
2206 VISIT_SEQ(c, stmt, s->v.While.orelse);
2207 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210}
2211
2212static int
2213compiler_continue(struct compiler *c)
2214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2216 static const char IN_FINALLY_ERROR_MSG[] =
2217 "'continue' not supported inside 'finally' clause";
2218 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (!c->u->u_nfblocks)
2221 return compiler_error(c, LOOP_ERROR_MSG);
2222 i = c->u->u_nfblocks - 1;
2223 switch (c->u->u_fblock[i].fb_type) {
2224 case LOOP:
2225 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2226 break;
2227 case EXCEPT:
2228 case FINALLY_TRY:
2229 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2230 /* Prevent continue anywhere under a finally
2231 even if hidden in a sub-try or except. */
2232 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2233 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2234 }
2235 if (i == -1)
2236 return compiler_error(c, LOOP_ERROR_MSG);
2237 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2238 break;
2239 case FINALLY_END:
2240 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2241 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244}
2245
2246/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247
2248 SETUP_FINALLY L
2249 <code for body>
2250 POP_BLOCK
2251 LOAD_CONST <None>
2252 L: <code for finalbody>
2253 END_FINALLY
2254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 The special instructions use the block stack. Each block
2256 stack entry contains the instruction that created it (here
2257 SETUP_FINALLY), the level of the value stack at the time the
2258 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Pushes the current value stack level and the label
2262 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 Pops en entry from the block stack, and pops the value
2265 stack until its level is the same as indicated on the
2266 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Pops a variable number of entries from the *value* stack
2269 and re-raises the exception they specify. The number of
2270 entries popped depends on the (pseudo) exception type.
2271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 The block stack is unwound when an exception is raised:
2273 when a SETUP_FINALLY entry is found, the exception is pushed
2274 onto the value stack (and the exception condition is cleared),
2275 and the interpreter jumps to the label gotten from the block
2276 stack.
2277*/
2278
2279static int
2280compiler_try_finally(struct compiler *c, stmt_ty s)
2281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 basicblock *body, *end;
2283 body = compiler_new_block(c);
2284 end = compiler_new_block(c);
2285 if (body == NULL || end == NULL)
2286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 ADDOP_JREL(c, SETUP_FINALLY, end);
2289 compiler_use_next_block(c, body);
2290 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2291 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002292 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2293 if (!compiler_try_except(c, s))
2294 return 0;
2295 }
2296 else {
2297 VISIT_SEQ(c, stmt, s->v.Try.body);
2298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 ADDOP(c, POP_BLOCK);
2300 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2303 compiler_use_next_block(c, end);
2304 if (!compiler_push_fblock(c, FINALLY_END, end))
2305 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002306 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 ADDOP(c, END_FINALLY);
2308 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311}
2312
2313/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002314 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315 (The contents of the value stack is shown in [], with the top
2316 at the right; 'tb' is trace-back info, 'val' the exception's
2317 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318
2319 Value stack Label Instruction Argument
2320 [] SETUP_EXCEPT L1
2321 [] <code for S>
2322 [] POP_BLOCK
2323 [] JUMP_FORWARD L0
2324
2325 [tb, val, exc] L1: DUP )
2326 [tb, val, exc, exc] <evaluate E1> )
2327 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2328 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2329 [tb, val, exc] POP
2330 [tb, val] <assign to V1> (or POP if no V1)
2331 [tb] POP
2332 [] <code for S1>
2333 JUMP_FORWARD L0
2334
2335 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 .............................etc.......................
2337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2339
2340 [] L0: <next statement>
2341
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 Of course, parts are not generated if Vi or Ei is not present.
2343*/
2344static int
2345compiler_try_except(struct compiler *c, stmt_ty s)
2346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002348 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 body = compiler_new_block(c);
2351 except = compiler_new_block(c);
2352 orelse = compiler_new_block(c);
2353 end = compiler_new_block(c);
2354 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2355 return 0;
2356 ADDOP_JREL(c, SETUP_EXCEPT, except);
2357 compiler_use_next_block(c, body);
2358 if (!compiler_push_fblock(c, EXCEPT, body))
2359 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002360 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 ADDOP(c, POP_BLOCK);
2362 compiler_pop_fblock(c, EXCEPT, body);
2363 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002364 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 compiler_use_next_block(c, except);
2366 for (i = 0; i < n; i++) {
2367 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002368 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 if (!handler->v.ExceptHandler.type && i < n-1)
2370 return compiler_error(c, "default 'except:' must be last");
2371 c->u->u_lineno_set = 0;
2372 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002373 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 except = compiler_new_block(c);
2375 if (except == NULL)
2376 return 0;
2377 if (handler->v.ExceptHandler.type) {
2378 ADDOP(c, DUP_TOP);
2379 VISIT(c, expr, handler->v.ExceptHandler.type);
2380 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2381 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2382 }
2383 ADDOP(c, POP_TOP);
2384 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002385 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002386
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002387 cleanup_end = compiler_new_block(c);
2388 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002389 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002390 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002391
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002392 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2393 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002395 /*
2396 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002397 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002398 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002399 try:
2400 # body
2401 finally:
2402 name = None
2403 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002404 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002406 /* second try: */
2407 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2408 compiler_use_next_block(c, cleanup_body);
2409 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2410 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002412 /* second # body */
2413 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2414 ADDOP(c, POP_BLOCK);
2415 ADDOP(c, POP_EXCEPT);
2416 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002418 /* finally: */
2419 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2420 compiler_use_next_block(c, cleanup_end);
2421 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2422 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002424 /* name = None */
2425 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2426 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002428 /* del name */
2429 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002431 ADDOP(c, END_FINALLY);
2432 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 }
2434 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002435 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002437 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002438 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002439 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440
Guido van Rossumb940e112007-01-10 16:19:56 +00002441 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002442 ADDOP(c, POP_TOP);
2443 compiler_use_next_block(c, cleanup_body);
2444 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2445 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002447 ADDOP(c, POP_EXCEPT);
2448 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 }
2450 ADDOP_JREL(c, JUMP_FORWARD, end);
2451 compiler_use_next_block(c, except);
2452 }
2453 ADDOP(c, END_FINALLY);
2454 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002455 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 compiler_use_next_block(c, end);
2457 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458}
2459
2460static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002461compiler_try(struct compiler *c, stmt_ty s) {
2462 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2463 return compiler_try_finally(c, s);
2464 else
2465 return compiler_try_except(c, s);
2466}
2467
2468
2469static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470compiler_import_as(struct compiler *c, identifier name, identifier asname)
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* The IMPORT_NAME opcode was already generated. This function
2473 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 If there is a dot in name, we need to split it and emit a
2476 LOAD_ATTR for each name.
2477 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2479 PyUnicode_GET_LENGTH(name), 1);
2480 if (dot == -2)
2481 return -1;
2482 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 Py_ssize_t pos = dot + 1;
2485 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 dot = PyUnicode_FindChar(name, '.', pos,
2488 PyUnicode_GET_LENGTH(name), 1);
2489 if (dot == -2)
2490 return -1;
2491 attr = PyUnicode_Substring(name, pos,
2492 (dot != -1) ? dot :
2493 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (!attr)
2495 return -1;
2496 ADDOP_O(c, LOAD_ATTR, attr, names);
2497 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002498 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 }
2500 }
2501 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502}
2503
2504static int
2505compiler_import(struct compiler *c, stmt_ty s)
2506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* The Import node stores a module name like a.b.c as a single
2508 string. This is convenient for all cases except
2509 import a.b.c as d
2510 where we need to parse that string to extract the individual
2511 module names.
2512 XXX Perhaps change the representation to make this case simpler?
2513 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002514 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 for (i = 0; i < n; i++) {
2517 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2518 int r;
2519 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 level = PyLong_FromLong(0);
2522 if (level == NULL)
2523 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 ADDOP_O(c, LOAD_CONST, level, consts);
2526 Py_DECREF(level);
2527 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2528 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (alias->asname) {
2531 r = compiler_import_as(c, alias->name, alias->asname);
2532 if (!r)
2533 return r;
2534 }
2535 else {
2536 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002537 Py_ssize_t dot = PyUnicode_FindChar(
2538 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002539 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002540 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002541 if (tmp == NULL)
2542 return 0;
2543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 Py_DECREF(tmp);
2547 }
2548 if (!r)
2549 return r;
2550 }
2551 }
2552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553}
2554
2555static int
2556compiler_from_import(struct compiler *c, stmt_ty s)
2557{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002558 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 PyObject *names = PyTuple_New(n);
2561 PyObject *level;
2562 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (!empty_string) {
2565 empty_string = PyUnicode_FromString("");
2566 if (!empty_string)
2567 return 0;
2568 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 if (!names)
2571 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 level = PyLong_FromLong(s->v.ImportFrom.level);
2574 if (!level) {
2575 Py_DECREF(names);
2576 return 0;
2577 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 /* build up the names */
2580 for (i = 0; i < n; i++) {
2581 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2582 Py_INCREF(alias->name);
2583 PyTuple_SET_ITEM(names, i, alias->name);
2584 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2587 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2588 Py_DECREF(level);
2589 Py_DECREF(names);
2590 return compiler_error(c, "from __future__ imports must occur "
2591 "at the beginning of the file");
2592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 ADDOP_O(c, LOAD_CONST, level, consts);
2595 Py_DECREF(level);
2596 ADDOP_O(c, LOAD_CONST, names, consts);
2597 Py_DECREF(names);
2598 if (s->v.ImportFrom.module) {
2599 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2600 }
2601 else {
2602 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2603 }
2604 for (i = 0; i < n; i++) {
2605 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2606 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 assert(n == 1);
2610 ADDOP(c, IMPORT_STAR);
2611 return 1;
2612 }
2613
2614 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2615 store_name = alias->name;
2616 if (alias->asname)
2617 store_name = alias->asname;
2618
2619 if (!compiler_nameop(c, store_name, Store)) {
2620 Py_DECREF(names);
2621 return 0;
2622 }
2623 }
2624 /* remove imported module */
2625 ADDOP(c, POP_TOP);
2626 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627}
2628
2629static int
2630compiler_assert(struct compiler *c, stmt_ty s)
2631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 static PyObject *assertion_error = NULL;
2633 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002634 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Georg Brandl8334fd92010-12-04 10:26:46 +00002636 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return 1;
2638 if (assertion_error == NULL) {
2639 assertion_error = PyUnicode_InternFromString("AssertionError");
2640 if (assertion_error == NULL)
2641 return 0;
2642 }
2643 if (s->v.Assert.test->kind == Tuple_kind &&
2644 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002645 msg = PyUnicode_FromString("assertion is always true, "
2646 "perhaps remove parentheses?");
2647 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002649 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2650 c->c_filename, c->u->u_lineno,
2651 NULL, NULL) == -1) {
2652 Py_DECREF(msg);
2653 return 0;
2654 }
2655 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 }
2657 VISIT(c, expr, s->v.Assert.test);
2658 end = compiler_new_block(c);
2659 if (end == NULL)
2660 return 0;
2661 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2662 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2663 if (s->v.Assert.msg) {
2664 VISIT(c, expr, s->v.Assert.msg);
2665 ADDOP_I(c, CALL_FUNCTION, 1);
2666 }
2667 ADDOP_I(c, RAISE_VARARGS, 1);
2668 compiler_use_next_block(c, end);
2669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670}
2671
2672static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002673compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2674{
2675 if (c->c_interactive && c->c_nestlevel <= 1) {
2676 VISIT(c, expr, value);
2677 ADDOP(c, PRINT_EXPR);
2678 return 1;
2679 }
2680
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002681 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002682 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002683 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002684 }
2685
2686 VISIT(c, expr, value);
2687 ADDOP(c, POP_TOP);
2688 return 1;
2689}
2690
2691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692compiler_visit_stmt(struct compiler *c, stmt_ty s)
2693{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002694 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 /* Always assign a lineno to the next instruction for a stmt. */
2697 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002698 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 switch (s->kind) {
2702 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002703 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 case ClassDef_kind:
2705 return compiler_class(c, s);
2706 case Return_kind:
2707 if (c->u->u_ste->ste_type != FunctionBlock)
2708 return compiler_error(c, "'return' outside function");
2709 if (s->v.Return.value) {
2710 VISIT(c, expr, s->v.Return.value);
2711 }
2712 else
2713 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2714 ADDOP(c, RETURN_VALUE);
2715 break;
2716 case Delete_kind:
2717 VISIT_SEQ(c, expr, s->v.Delete.targets)
2718 break;
2719 case Assign_kind:
2720 n = asdl_seq_LEN(s->v.Assign.targets);
2721 VISIT(c, expr, s->v.Assign.value);
2722 for (i = 0; i < n; i++) {
2723 if (i < n - 1)
2724 ADDOP(c, DUP_TOP);
2725 VISIT(c, expr,
2726 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2727 }
2728 break;
2729 case AugAssign_kind:
2730 return compiler_augassign(c, s);
2731 case For_kind:
2732 return compiler_for(c, s);
2733 case While_kind:
2734 return compiler_while(c, s);
2735 case If_kind:
2736 return compiler_if(c, s);
2737 case Raise_kind:
2738 n = 0;
2739 if (s->v.Raise.exc) {
2740 VISIT(c, expr, s->v.Raise.exc);
2741 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002742 if (s->v.Raise.cause) {
2743 VISIT(c, expr, s->v.Raise.cause);
2744 n++;
2745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002747 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002749 case Try_kind:
2750 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 case Assert_kind:
2752 return compiler_assert(c, s);
2753 case Import_kind:
2754 return compiler_import(c, s);
2755 case ImportFrom_kind:
2756 return compiler_from_import(c, s);
2757 case Global_kind:
2758 case Nonlocal_kind:
2759 break;
2760 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002761 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 case Pass_kind:
2763 break;
2764 case Break_kind:
2765 if (!compiler_in_loop(c))
2766 return compiler_error(c, "'break' outside loop");
2767 ADDOP(c, BREAK_LOOP);
2768 break;
2769 case Continue_kind:
2770 return compiler_continue(c);
2771 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002772 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002773 case AsyncFunctionDef_kind:
2774 return compiler_function(c, s, 1);
2775 case AsyncWith_kind:
2776 return compiler_async_with(c, s, 0);
2777 case AsyncFor_kind:
2778 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 }
Yury Selivanov75445082015-05-11 22:57:16 -04002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782}
2783
2784static int
2785unaryop(unaryop_ty op)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 switch (op) {
2788 case Invert:
2789 return UNARY_INVERT;
2790 case Not:
2791 return UNARY_NOT;
2792 case UAdd:
2793 return UNARY_POSITIVE;
2794 case USub:
2795 return UNARY_NEGATIVE;
2796 default:
2797 PyErr_Format(PyExc_SystemError,
2798 "unary op %d should not be possible", op);
2799 return 0;
2800 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801}
2802
2803static int
2804binop(struct compiler *c, operator_ty op)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 switch (op) {
2807 case Add:
2808 return BINARY_ADD;
2809 case Sub:
2810 return BINARY_SUBTRACT;
2811 case Mult:
2812 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002813 case MatMult:
2814 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 case Div:
2816 return BINARY_TRUE_DIVIDE;
2817 case Mod:
2818 return BINARY_MODULO;
2819 case Pow:
2820 return BINARY_POWER;
2821 case LShift:
2822 return BINARY_LSHIFT;
2823 case RShift:
2824 return BINARY_RSHIFT;
2825 case BitOr:
2826 return BINARY_OR;
2827 case BitXor:
2828 return BINARY_XOR;
2829 case BitAnd:
2830 return BINARY_AND;
2831 case FloorDiv:
2832 return BINARY_FLOOR_DIVIDE;
2833 default:
2834 PyErr_Format(PyExc_SystemError,
2835 "binary op %d should not be possible", op);
2836 return 0;
2837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838}
2839
2840static int
2841cmpop(cmpop_ty op)
2842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 switch (op) {
2844 case Eq:
2845 return PyCmp_EQ;
2846 case NotEq:
2847 return PyCmp_NE;
2848 case Lt:
2849 return PyCmp_LT;
2850 case LtE:
2851 return PyCmp_LE;
2852 case Gt:
2853 return PyCmp_GT;
2854 case GtE:
2855 return PyCmp_GE;
2856 case Is:
2857 return PyCmp_IS;
2858 case IsNot:
2859 return PyCmp_IS_NOT;
2860 case In:
2861 return PyCmp_IN;
2862 case NotIn:
2863 return PyCmp_NOT_IN;
2864 default:
2865 return PyCmp_BAD;
2866 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867}
2868
2869static int
2870inplace_binop(struct compiler *c, operator_ty op)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 switch (op) {
2873 case Add:
2874 return INPLACE_ADD;
2875 case Sub:
2876 return INPLACE_SUBTRACT;
2877 case Mult:
2878 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002879 case MatMult:
2880 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 case Div:
2882 return INPLACE_TRUE_DIVIDE;
2883 case Mod:
2884 return INPLACE_MODULO;
2885 case Pow:
2886 return INPLACE_POWER;
2887 case LShift:
2888 return INPLACE_LSHIFT;
2889 case RShift:
2890 return INPLACE_RSHIFT;
2891 case BitOr:
2892 return INPLACE_OR;
2893 case BitXor:
2894 return INPLACE_XOR;
2895 case BitAnd:
2896 return INPLACE_AND;
2897 case FloorDiv:
2898 return INPLACE_FLOOR_DIVIDE;
2899 default:
2900 PyErr_Format(PyExc_SystemError,
2901 "inplace binary op %d should not be possible", op);
2902 return 0;
2903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904}
2905
2906static int
2907compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2908{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002909 int op, scope;
2910 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyObject *dict = c->u->u_names;
2914 PyObject *mangled;
2915 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 mangled = _Py_Mangle(c->u->u_private, name);
2918 if (!mangled)
2919 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002920
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002921 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2922 PyUnicode_CompareWithASCIIString(name, "True") &&
2923 PyUnicode_CompareWithASCIIString(name, "False"));
2924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 op = 0;
2926 optype = OP_NAME;
2927 scope = PyST_GetScope(c->u->u_ste, mangled);
2928 switch (scope) {
2929 case FREE:
2930 dict = c->u->u_freevars;
2931 optype = OP_DEREF;
2932 break;
2933 case CELL:
2934 dict = c->u->u_cellvars;
2935 optype = OP_DEREF;
2936 break;
2937 case LOCAL:
2938 if (c->u->u_ste->ste_type == FunctionBlock)
2939 optype = OP_FAST;
2940 break;
2941 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002942 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 optype = OP_GLOBAL;
2944 break;
2945 case GLOBAL_EXPLICIT:
2946 optype = OP_GLOBAL;
2947 break;
2948 default:
2949 /* scope can be 0 */
2950 break;
2951 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 switch (optype) {
2957 case OP_DEREF:
2958 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002959 case Load:
2960 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2961 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 case Store: op = STORE_DEREF; break;
2963 case AugLoad:
2964 case AugStore:
2965 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002966 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 case Param:
2968 default:
2969 PyErr_SetString(PyExc_SystemError,
2970 "param invalid for deref variable");
2971 return 0;
2972 }
2973 break;
2974 case OP_FAST:
2975 switch (ctx) {
2976 case Load: op = LOAD_FAST; break;
2977 case Store: op = STORE_FAST; break;
2978 case Del: op = DELETE_FAST; break;
2979 case AugLoad:
2980 case AugStore:
2981 break;
2982 case Param:
2983 default:
2984 PyErr_SetString(PyExc_SystemError,
2985 "param invalid for local variable");
2986 return 0;
2987 }
2988 ADDOP_O(c, op, mangled, varnames);
2989 Py_DECREF(mangled);
2990 return 1;
2991 case OP_GLOBAL:
2992 switch (ctx) {
2993 case Load: op = LOAD_GLOBAL; break;
2994 case Store: op = STORE_GLOBAL; break;
2995 case Del: op = DELETE_GLOBAL; break;
2996 case AugLoad:
2997 case AugStore:
2998 break;
2999 case Param:
3000 default:
3001 PyErr_SetString(PyExc_SystemError,
3002 "param invalid for global variable");
3003 return 0;
3004 }
3005 break;
3006 case OP_NAME:
3007 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003008 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 case Store: op = STORE_NAME; break;
3010 case Del: op = DELETE_NAME; break;
3011 case AugLoad:
3012 case AugStore:
3013 break;
3014 case Param:
3015 default:
3016 PyErr_SetString(PyExc_SystemError,
3017 "param invalid for name variable");
3018 return 0;
3019 }
3020 break;
3021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 assert(op);
3024 arg = compiler_add_o(c, dict, mangled);
3025 Py_DECREF(mangled);
3026 if (arg < 0)
3027 return 0;
3028 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029}
3030
3031static int
3032compiler_boolop(struct compiler *c, expr_ty e)
3033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003035 int jumpi;
3036 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 assert(e->kind == BoolOp_kind);
3040 if (e->v.BoolOp.op == And)
3041 jumpi = JUMP_IF_FALSE_OR_POP;
3042 else
3043 jumpi = JUMP_IF_TRUE_OR_POP;
3044 end = compiler_new_block(c);
3045 if (end == NULL)
3046 return 0;
3047 s = e->v.BoolOp.values;
3048 n = asdl_seq_LEN(s) - 1;
3049 assert(n >= 0);
3050 for (i = 0; i < n; ++i) {
3051 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3052 ADDOP_JABS(c, jumpi, end);
3053 }
3054 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3055 compiler_use_next_block(c, end);
3056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057}
3058
3059static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003060starunpack_helper(struct compiler *c, asdl_seq *elts,
3061 int single_op, int inner_op, int outer_op)
3062{
3063 Py_ssize_t n = asdl_seq_LEN(elts);
3064 Py_ssize_t i, nsubitems = 0, nseen = 0;
3065 for (i = 0; i < n; i++) {
3066 expr_ty elt = asdl_seq_GET(elts, i);
3067 if (elt->kind == Starred_kind) {
3068 if (nseen) {
3069 ADDOP_I(c, inner_op, nseen);
3070 nseen = 0;
3071 nsubitems++;
3072 }
3073 VISIT(c, expr, elt->v.Starred.value);
3074 nsubitems++;
3075 }
3076 else {
3077 VISIT(c, expr, elt);
3078 nseen++;
3079 }
3080 }
3081 if (nsubitems) {
3082 if (nseen) {
3083 ADDOP_I(c, inner_op, nseen);
3084 nsubitems++;
3085 }
3086 ADDOP_I(c, outer_op, nsubitems);
3087 }
3088 else
3089 ADDOP_I(c, single_op, nseen);
3090 return 1;
3091}
3092
3093static int
3094assignment_helper(struct compiler *c, asdl_seq *elts)
3095{
3096 Py_ssize_t n = asdl_seq_LEN(elts);
3097 Py_ssize_t i;
3098 int seen_star = 0;
3099 for (i = 0; i < n; i++) {
3100 expr_ty elt = asdl_seq_GET(elts, i);
3101 if (elt->kind == Starred_kind && !seen_star) {
3102 if ((i >= (1 << 8)) ||
3103 (n-i-1 >= (INT_MAX >> 8)))
3104 return compiler_error(c,
3105 "too many expressions in "
3106 "star-unpacking assignment");
3107 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3108 seen_star = 1;
3109 asdl_seq_SET(elts, i, elt->v.Starred.value);
3110 }
3111 else if (elt->kind == Starred_kind) {
3112 return compiler_error(c,
3113 "two starred expressions in assignment");
3114 }
3115 }
3116 if (!seen_star) {
3117 ADDOP_I(c, UNPACK_SEQUENCE, n);
3118 }
3119 VISIT_SEQ(c, expr, elts);
3120 return 1;
3121}
3122
3123static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003124compiler_list(struct compiler *c, expr_ty e)
3125{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003126 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003128 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003130 else if (e->v.List.ctx == Load) {
3131 return starunpack_helper(c, elts,
3132 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003134 else
3135 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137}
3138
3139static int
3140compiler_tuple(struct compiler *c, expr_ty e)
3141{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003142 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003144 return assignment_helper(c, elts);
3145 }
3146 else if (e->v.Tuple.ctx == Load) {
3147 return starunpack_helper(c, elts,
3148 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3149 }
3150 else
3151 VISIT_SEQ(c, expr, elts);
3152 return 1;
3153}
3154
3155static int
3156compiler_set(struct compiler *c, expr_ty e)
3157{
3158 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3159 BUILD_SET, BUILD_SET_UNPACK);
3160}
3161
3162static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003163are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3164{
3165 Py_ssize_t i;
3166 for (i = begin; i < end; i++) {
3167 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3168 if (key == NULL || !is_const(key))
3169 return 0;
3170 }
3171 return 1;
3172}
3173
3174static int
3175compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3176{
3177 Py_ssize_t i, n = end - begin;
3178 PyObject *keys, *key;
3179 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3180 for (i = begin; i < end; i++) {
3181 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3182 }
3183 keys = PyTuple_New(n);
3184 if (keys == NULL) {
3185 return 0;
3186 }
3187 for (i = begin; i < end; i++) {
3188 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3189 Py_INCREF(key);
3190 PyTuple_SET_ITEM(keys, i - begin, key);
3191 }
3192 ADDOP_N(c, LOAD_CONST, keys, consts);
3193 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3194 }
3195 else {
3196 for (i = begin; i < end; i++) {
3197 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3198 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3199 }
3200 ADDOP_I(c, BUILD_MAP, n);
3201 }
3202 return 1;
3203}
3204
3205static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003206compiler_dict(struct compiler *c, expr_ty e)
3207{
Victor Stinner976bb402016-03-23 11:36:19 +01003208 Py_ssize_t i, n, elements;
3209 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003210 int is_unpacking = 0;
3211 n = asdl_seq_LEN(e->v.Dict.values);
3212 containers = 0;
3213 elements = 0;
3214 for (i = 0; i < n; i++) {
3215 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3216 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003217 if (!compiler_subdict(c, e, i - elements, i))
3218 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003219 containers++;
3220 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003222 if (is_unpacking) {
3223 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3224 containers++;
3225 }
3226 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003227 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 }
3229 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003230 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003231 if (!compiler_subdict(c, e, n - elements, n))
3232 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003233 containers++;
3234 }
3235 /* If there is more than one dict, they need to be merged into a new
3236 * dict. If there is one dict and it's an unpacking, then it needs
3237 * to be copied into a new dict." */
3238 while (containers > 1 || is_unpacking) {
3239 int oparg = containers < 255 ? containers : 255;
3240 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3241 containers -= (oparg - 1);
3242 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 }
3244 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245}
3246
3247static int
3248compiler_compare(struct compiler *c, expr_ty e)
3249{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003250 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3254 VISIT(c, expr, e->v.Compare.left);
3255 n = asdl_seq_LEN(e->v.Compare.ops);
3256 assert(n > 0);
3257 if (n > 1) {
3258 cleanup = compiler_new_block(c);
3259 if (cleanup == NULL)
3260 return 0;
3261 VISIT(c, expr,
3262 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3263 }
3264 for (i = 1; i < n; i++) {
3265 ADDOP(c, DUP_TOP);
3266 ADDOP(c, ROT_THREE);
3267 ADDOP_I(c, COMPARE_OP,
3268 cmpop((cmpop_ty)(asdl_seq_GET(
3269 e->v.Compare.ops, i - 1))));
3270 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3271 NEXT_BLOCK(c);
3272 if (i < (n - 1))
3273 VISIT(c, expr,
3274 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3275 }
3276 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3277 ADDOP_I(c, COMPARE_OP,
3278 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3279 if (n > 1) {
3280 basicblock *end = compiler_new_block(c);
3281 if (end == NULL)
3282 return 0;
3283 ADDOP_JREL(c, JUMP_FORWARD, end);
3284 compiler_use_next_block(c, cleanup);
3285 ADDOP(c, ROT_TWO);
3286 ADDOP(c, POP_TOP);
3287 compiler_use_next_block(c, end);
3288 }
3289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290}
3291
3292static int
3293compiler_call(struct compiler *c, expr_ty e)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 VISIT(c, expr, e->v.Call.func);
3296 return compiler_call_helper(c, 0,
3297 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003298 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003299}
3300
Eric V. Smith235a6f02015-09-19 14:51:32 -04003301static int
3302compiler_joined_str(struct compiler *c, expr_ty e)
3303{
3304 /* Concatenate parts of a string using ''.join(parts). There are
3305 probably better ways of doing this.
3306
3307 This is used for constructs like "'x=' f'{42}'", which have to
3308 be evaluated at compile time. */
3309
3310 static PyObject *empty_string;
3311 static PyObject *join_string;
3312
3313 if (!empty_string) {
3314 empty_string = PyUnicode_FromString("");
3315 if (!empty_string)
3316 return 0;
3317 }
3318 if (!join_string) {
3319 join_string = PyUnicode_FromString("join");
3320 if (!join_string)
3321 return 0;
3322 }
3323
3324 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3325 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3326 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3327 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3328 ADDOP_I(c, CALL_FUNCTION, 1);
3329 return 1;
3330}
3331
Eric V. Smitha78c7952015-11-03 12:45:05 -05003332/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003333static int
3334compiler_formatted_value(struct compiler *c, expr_ty e)
3335{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003336 /* Our oparg encodes 2 pieces of information: the conversion
3337 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003338
Eric V. Smitha78c7952015-11-03 12:45:05 -05003339 Convert the conversion char to 2 bits:
3340 None: 000 0x0 FVC_NONE
3341 !s : 001 0x1 FVC_STR
3342 !r : 010 0x2 FVC_REPR
3343 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003344
Eric V. Smitha78c7952015-11-03 12:45:05 -05003345 next bit is whether or not we have a format spec:
3346 yes : 100 0x4
3347 no : 000 0x0
3348 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003349
Eric V. Smitha78c7952015-11-03 12:45:05 -05003350 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003351
Eric V. Smitha78c7952015-11-03 12:45:05 -05003352 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003353 VISIT(c, expr, e->v.FormattedValue.value);
3354
Eric V. Smitha78c7952015-11-03 12:45:05 -05003355 switch (e->v.FormattedValue.conversion) {
3356 case 's': oparg = FVC_STR; break;
3357 case 'r': oparg = FVC_REPR; break;
3358 case 'a': oparg = FVC_ASCII; break;
3359 case -1: oparg = FVC_NONE; break;
3360 default:
3361 PyErr_SetString(PyExc_SystemError,
3362 "Unrecognized conversion character");
3363 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003364 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003365 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003366 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003367 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003368 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003369 }
3370
Eric V. Smitha78c7952015-11-03 12:45:05 -05003371 /* And push our opcode and oparg */
3372 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003373 return 1;
3374}
3375
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003376static int
3377compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3378{
3379 Py_ssize_t i, n = end - begin;
3380 keyword_ty kw;
3381 PyObject *keys, *key;
3382 assert(n > 0);
3383 if (n > 1) {
3384 for (i = begin; i < end; i++) {
3385 kw = asdl_seq_GET(keywords, i);
3386 VISIT(c, expr, kw->value);
3387 }
3388 keys = PyTuple_New(n);
3389 if (keys == NULL) {
3390 return 0;
3391 }
3392 for (i = begin; i < end; i++) {
3393 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3394 Py_INCREF(key);
3395 PyTuple_SET_ITEM(keys, i - begin, key);
3396 }
3397 ADDOP_N(c, LOAD_CONST, keys, consts);
3398 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3399 }
3400 else {
3401 /* a for loop only executes once */
3402 for (i = begin; i < end; i++) {
3403 kw = asdl_seq_GET(keywords, i);
3404 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3405 VISIT(c, expr, kw->value);
3406 }
3407 ADDOP_I(c, BUILD_MAP, n);
3408 }
3409 return 1;
3410}
3411
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003412/* shared code between compiler_call and compiler_class */
3413static int
3414compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003415 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003416 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003417 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003420 Py_ssize_t nelts, i, nseen;
3421 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003422
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003423 /* the number of tuples and dictionaries on the stack */
3424 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3425
3426 nkw = 0;
3427 nseen = 0; /* the number of positional arguments on the stack */
3428 nelts = asdl_seq_LEN(args);
3429 for (i = 0; i < nelts; i++) {
3430 expr_ty elt = asdl_seq_GET(args, i);
3431 if (elt->kind == Starred_kind) {
3432 /* A star-arg. If we've seen positional arguments,
3433 pack the positional arguments into a
3434 tuple. */
3435 if (nseen) {
3436 ADDOP_I(c, BUILD_TUPLE, nseen);
3437 nseen = 0;
3438 nsubargs++;
3439 }
3440 VISIT(c, expr, elt->v.Starred.value);
3441 nsubargs++;
3442 }
3443 else if (nsubargs) {
3444 /* We've seen star-args already, so we
3445 count towards items-to-pack-into-tuple. */
3446 VISIT(c, expr, elt);
3447 nseen++;
3448 }
3449 else {
3450 /* Positional arguments before star-arguments
3451 are left on the stack. */
3452 VISIT(c, expr, elt);
3453 n++;
3454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003456 if (nseen) {
3457 /* Pack up any trailing positional arguments. */
3458 ADDOP_I(c, BUILD_TUPLE, nseen);
3459 nsubargs++;
3460 }
3461 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003463 if (nsubargs > 1) {
3464 /* If we ended up with more than one stararg, we need
3465 to concatenate them into a single sequence. */
3466 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003469
3470 /* Same dance again for keyword arguments */
3471 nseen = 0; /* the number of keyword arguments on the stack following */
3472 nelts = asdl_seq_LEN(keywords);
3473 for (i = 0; i < nelts; i++) {
3474 keyword_ty kw = asdl_seq_GET(keywords, i);
3475 if (kw->arg == NULL) {
3476 /* A keyword argument unpacking. */
3477 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003478 if (nsubkwargs) {
3479 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3480 return 0;
3481 nsubkwargs++;
3482 }
3483 else {
3484 Py_ssize_t j;
3485 for (j = 0; j < nseen; j++) {
3486 VISIT(c, keyword, asdl_seq_GET(keywords, j));
3487 }
3488 nkw = nseen;
3489 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003490 nseen = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003491 }
3492 VISIT(c, expr, kw->value);
3493 nsubkwargs++;
3494 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003495 else {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003496 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003497 }
3498 }
3499 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003500 if (nsubkwargs) {
3501 /* Pack up any trailing keyword arguments. */
3502 if (!compiler_subkwargs(c, keywords, nelts - nseen, nelts))
3503 return 0;
3504 nsubkwargs++;
3505 }
3506 else {
3507 VISIT_SEQ(c, keyword, keywords);
3508 nkw = nseen;
3509 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003510 }
3511 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513 if (nsubkwargs > 1) {
3514 /* Pack it all up */
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03003515 int function_pos = n + (code & 1) + 2 * nkw + 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003516 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003519 assert(n < 1<<8);
3520 assert(nkw < 1<<24);
3521 n |= nkw << 8;
3522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 switch (code) {
3524 case 0:
3525 ADDOP_I(c, CALL_FUNCTION, n);
3526 break;
3527 case 1:
3528 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3529 break;
3530 case 2:
3531 ADDOP_I(c, CALL_FUNCTION_KW, n);
3532 break;
3533 case 3:
3534 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3535 break;
3536 }
3537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538}
3539
Nick Coghlan650f0d02007-04-15 12:05:43 +00003540
3541/* List and set comprehensions and generator expressions work by creating a
3542 nested function to perform the actual iteration. This means that the
3543 iteration variables don't leak into the current scope.
3544 The defined function is called immediately following its definition, with the
3545 result of that call being the result of the expression.
3546 The LC/SC version returns the populated container, while the GE version is
3547 flagged in symtable.c as a generator, so it returns the generator object
3548 when the function is called.
3549 This code *knows* that the loop cannot contain break, continue, or return,
3550 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3551
3552 Possible cleanups:
3553 - iterate over the generator sequence instead of using recursion
3554*/
3555
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557compiler_comprehension_generator(struct compiler *c,
3558 asdl_seq *generators, int gen_index,
3559 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 /* generate code for the iterator, then each of the ifs,
3562 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 comprehension_ty gen;
3565 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003566 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 start = compiler_new_block(c);
3569 skip = compiler_new_block(c);
3570 if_cleanup = compiler_new_block(c);
3571 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3574 anchor == NULL)
3575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 if (gen_index == 0) {
3580 /* Receive outermost iter as an implicit argument */
3581 c->u->u_argcount = 1;
3582 ADDOP_I(c, LOAD_FAST, 0);
3583 }
3584 else {
3585 /* Sub-iter - calculate on the fly */
3586 VISIT(c, expr, gen->iter);
3587 ADDOP(c, GET_ITER);
3588 }
3589 compiler_use_next_block(c, start);
3590 ADDOP_JREL(c, FOR_ITER, anchor);
3591 NEXT_BLOCK(c);
3592 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 /* XXX this needs to be cleaned up...a lot! */
3595 n = asdl_seq_LEN(gen->ifs);
3596 for (i = 0; i < n; i++) {
3597 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3598 VISIT(c, expr, e);
3599 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3600 NEXT_BLOCK(c);
3601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 if (++gen_index < asdl_seq_LEN(generators))
3604 if (!compiler_comprehension_generator(c,
3605 generators, gen_index,
3606 elt, val, type))
3607 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 /* only append after the last for generator */
3610 if (gen_index >= asdl_seq_LEN(generators)) {
3611 /* comprehension specific code */
3612 switch (type) {
3613 case COMP_GENEXP:
3614 VISIT(c, expr, elt);
3615 ADDOP(c, YIELD_VALUE);
3616 ADDOP(c, POP_TOP);
3617 break;
3618 case COMP_LISTCOMP:
3619 VISIT(c, expr, elt);
3620 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3621 break;
3622 case COMP_SETCOMP:
3623 VISIT(c, expr, elt);
3624 ADDOP_I(c, SET_ADD, gen_index + 1);
3625 break;
3626 case COMP_DICTCOMP:
3627 /* With 'd[k] = v', v is evaluated before k, so we do
3628 the same. */
3629 VISIT(c, expr, val);
3630 VISIT(c, expr, elt);
3631 ADDOP_I(c, MAP_ADD, gen_index + 1);
3632 break;
3633 default:
3634 return 0;
3635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 compiler_use_next_block(c, skip);
3638 }
3639 compiler_use_next_block(c, if_cleanup);
3640 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3641 compiler_use_next_block(c, anchor);
3642
3643 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644}
3645
3646static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003647compiler_comprehension(struct compiler *c, expr_ty e, int type,
3648 identifier name, asdl_seq *generators, expr_ty elt,
3649 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 PyCodeObject *co = NULL;
3652 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003653 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 outermost_iter = ((comprehension_ty)
3656 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003657
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003658 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3659 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 if (type != COMP_GENEXP) {
3663 int op;
3664 switch (type) {
3665 case COMP_LISTCOMP:
3666 op = BUILD_LIST;
3667 break;
3668 case COMP_SETCOMP:
3669 op = BUILD_SET;
3670 break;
3671 case COMP_DICTCOMP:
3672 op = BUILD_MAP;
3673 break;
3674 default:
3675 PyErr_Format(PyExc_SystemError,
3676 "unknown comprehension type %d", type);
3677 goto error_in_scope;
3678 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 ADDOP_I(c, op, 0);
3681 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (!compiler_comprehension_generator(c, generators, 0, elt,
3684 val, type))
3685 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 if (type != COMP_GENEXP) {
3688 ADDOP(c, RETURN_VALUE);
3689 }
3690
3691 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003692 qualname = c->u->u_qualname;
3693 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003695 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 goto error;
3697
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003698 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003700 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 Py_DECREF(co);
3702
3703 VISIT(c, expr, outermost_iter);
3704 ADDOP(c, GET_ITER);
3705 ADDOP_I(c, CALL_FUNCTION, 1);
3706 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003707error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003709error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003710 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 Py_XDECREF(co);
3712 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003713}
3714
3715static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716compiler_genexp(struct compiler *c, expr_ty e)
3717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 static identifier name;
3719 if (!name) {
3720 name = PyUnicode_FromString("<genexpr>");
3721 if (!name)
3722 return 0;
3723 }
3724 assert(e->kind == GeneratorExp_kind);
3725 return compiler_comprehension(c, e, COMP_GENEXP, name,
3726 e->v.GeneratorExp.generators,
3727 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728}
3729
3730static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003731compiler_listcomp(struct compiler *c, expr_ty e)
3732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 static identifier name;
3734 if (!name) {
3735 name = PyUnicode_FromString("<listcomp>");
3736 if (!name)
3737 return 0;
3738 }
3739 assert(e->kind == ListComp_kind);
3740 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3741 e->v.ListComp.generators,
3742 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003743}
3744
3745static int
3746compiler_setcomp(struct compiler *c, expr_ty e)
3747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 static identifier name;
3749 if (!name) {
3750 name = PyUnicode_FromString("<setcomp>");
3751 if (!name)
3752 return 0;
3753 }
3754 assert(e->kind == SetComp_kind);
3755 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3756 e->v.SetComp.generators,
3757 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003758}
3759
3760
3761static int
3762compiler_dictcomp(struct compiler *c, expr_ty e)
3763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 static identifier name;
3765 if (!name) {
3766 name = PyUnicode_FromString("<dictcomp>");
3767 if (!name)
3768 return 0;
3769 }
3770 assert(e->kind == DictComp_kind);
3771 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3772 e->v.DictComp.generators,
3773 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003774}
3775
3776
3777static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778compiler_visit_keyword(struct compiler *c, keyword_ty k)
3779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3781 VISIT(c, expr, k->value);
3782 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783}
3784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 whether they are true or false.
3787
3788 Return values: 1 for true, 0 for false, -1 for non-constant.
3789 */
3790
3791static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003792expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 char *id;
3795 switch (e->kind) {
3796 case Ellipsis_kind:
3797 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003798 case Constant_kind:
3799 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 case Num_kind:
3801 return PyObject_IsTrue(e->v.Num.n);
3802 case Str_kind:
3803 return PyObject_IsTrue(e->v.Str.s);
3804 case Name_kind:
3805 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003806 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003807 if (id && strcmp(id, "__debug__") == 0)
3808 return !c->c_optimize;
3809 return -1;
3810 case NameConstant_kind: {
3811 PyObject *o = e->v.NameConstant.value;
3812 if (o == Py_None)
3813 return 0;
3814 else if (o == Py_True)
3815 return 1;
3816 else if (o == Py_False)
3817 return 0;
3818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 default:
3820 return -1;
3821 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822}
3823
Yury Selivanov75445082015-05-11 22:57:16 -04003824
3825/*
3826 Implements the async with statement.
3827
3828 The semantics outlined in that PEP are as follows:
3829
3830 async with EXPR as VAR:
3831 BLOCK
3832
3833 It is implemented roughly as:
3834
3835 context = EXPR
3836 exit = context.__aexit__ # not calling it
3837 value = await context.__aenter__()
3838 try:
3839 VAR = value # if VAR present in the syntax
3840 BLOCK
3841 finally:
3842 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003843 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003844 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003845 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003846 if not (await exit(*exc)):
3847 raise
3848 */
3849static int
3850compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3851{
3852 basicblock *block, *finally;
3853 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3854
3855 assert(s->kind == AsyncWith_kind);
3856
3857 block = compiler_new_block(c);
3858 finally = compiler_new_block(c);
3859 if (!block || !finally)
3860 return 0;
3861
3862 /* Evaluate EXPR */
3863 VISIT(c, expr, item->context_expr);
3864
3865 ADDOP(c, BEFORE_ASYNC_WITH);
3866 ADDOP(c, GET_AWAITABLE);
3867 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3868 ADDOP(c, YIELD_FROM);
3869
3870 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3871
3872 /* SETUP_ASYNC_WITH pushes a finally block. */
3873 compiler_use_next_block(c, block);
3874 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3875 return 0;
3876 }
3877
3878 if (item->optional_vars) {
3879 VISIT(c, expr, item->optional_vars);
3880 }
3881 else {
3882 /* Discard result from context.__aenter__() */
3883 ADDOP(c, POP_TOP);
3884 }
3885
3886 pos++;
3887 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3888 /* BLOCK code */
3889 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3890 else if (!compiler_async_with(c, s, pos))
3891 return 0;
3892
3893 /* End of try block; start the finally block */
3894 ADDOP(c, POP_BLOCK);
3895 compiler_pop_fblock(c, FINALLY_TRY, block);
3896
3897 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3898 compiler_use_next_block(c, finally);
3899 if (!compiler_push_fblock(c, FINALLY_END, finally))
3900 return 0;
3901
3902 /* Finally block starts; context.__exit__ is on the stack under
3903 the exception or return information. Just issue our magic
3904 opcode. */
3905 ADDOP(c, WITH_CLEANUP_START);
3906
3907 ADDOP(c, GET_AWAITABLE);
3908 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3909 ADDOP(c, YIELD_FROM);
3910
3911 ADDOP(c, WITH_CLEANUP_FINISH);
3912
3913 /* Finally block ends. */
3914 ADDOP(c, END_FINALLY);
3915 compiler_pop_fblock(c, FINALLY_END, finally);
3916 return 1;
3917}
3918
3919
Guido van Rossumc2e20742006-02-27 22:32:47 +00003920/*
3921 Implements the with statement from PEP 343.
3922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003924
3925 with EXPR as VAR:
3926 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927
Guido van Rossumc2e20742006-02-27 22:32:47 +00003928 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929
Thomas Wouters477c8d52006-05-27 19:21:47 +00003930 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003931 exit = context.__exit__ # not calling it
3932 value = context.__enter__()
3933 try:
3934 VAR = value # if VAR present in the syntax
3935 BLOCK
3936 finally:
3937 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003938 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003939 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003940 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003941 exit(*exc)
3942 */
3943static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003944compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003945{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003946 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003947 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003948
3949 assert(s->kind == With_kind);
3950
Guido van Rossumc2e20742006-02-27 22:32:47 +00003951 block = compiler_new_block(c);
3952 finally = compiler_new_block(c);
3953 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003954 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003955
Thomas Wouters477c8d52006-05-27 19:21:47 +00003956 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003957 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003958 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003959
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003960 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003961 compiler_use_next_block(c, block);
3962 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003963 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003964 }
3965
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003966 if (item->optional_vars) {
3967 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003968 }
3969 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003971 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003972 }
3973
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003974 pos++;
3975 if (pos == asdl_seq_LEN(s->v.With.items))
3976 /* BLOCK code */
3977 VISIT_SEQ(c, stmt, s->v.With.body)
3978 else if (!compiler_with(c, s, pos))
3979 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003980
3981 /* End of try block; start the finally block */
3982 ADDOP(c, POP_BLOCK);
3983 compiler_pop_fblock(c, FINALLY_TRY, block);
3984
3985 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3986 compiler_use_next_block(c, finally);
3987 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003988 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003989
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003990 /* Finally block starts; context.__exit__ is on the stack under
3991 the exception or return information. Just issue our magic
3992 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003993 ADDOP(c, WITH_CLEANUP_START);
3994 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003995
3996 /* Finally block ends. */
3997 ADDOP(c, END_FINALLY);
3998 compiler_pop_fblock(c, FINALLY_END, finally);
3999 return 1;
4000}
4001
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002static int
4003compiler_visit_expr(struct compiler *c, expr_ty e)
4004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 /* If expr e has a different line number than the last expr/stmt,
4006 set a new line number for the next instruction.
4007 */
4008 if (e->lineno > c->u->u_lineno) {
4009 c->u->u_lineno = e->lineno;
4010 c->u->u_lineno_set = 0;
4011 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004012 /* Updating the column offset is always harmless. */
4013 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 switch (e->kind) {
4015 case BoolOp_kind:
4016 return compiler_boolop(c, e);
4017 case BinOp_kind:
4018 VISIT(c, expr, e->v.BinOp.left);
4019 VISIT(c, expr, e->v.BinOp.right);
4020 ADDOP(c, binop(c, e->v.BinOp.op));
4021 break;
4022 case UnaryOp_kind:
4023 VISIT(c, expr, e->v.UnaryOp.operand);
4024 ADDOP(c, unaryop(e->v.UnaryOp.op));
4025 break;
4026 case Lambda_kind:
4027 return compiler_lambda(c, e);
4028 case IfExp_kind:
4029 return compiler_ifexp(c, e);
4030 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004031 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004033 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 case GeneratorExp_kind:
4035 return compiler_genexp(c, e);
4036 case ListComp_kind:
4037 return compiler_listcomp(c, e);
4038 case SetComp_kind:
4039 return compiler_setcomp(c, e);
4040 case DictComp_kind:
4041 return compiler_dictcomp(c, e);
4042 case Yield_kind:
4043 if (c->u->u_ste->ste_type != FunctionBlock)
4044 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004045 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4046 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004047 if (e->v.Yield.value) {
4048 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 }
4050 else {
4051 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4052 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004053 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004055 case YieldFrom_kind:
4056 if (c->u->u_ste->ste_type != FunctionBlock)
4057 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004058
4059 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4060 return compiler_error(c, "'yield from' inside async function");
4061
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004062 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004063 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004064 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4065 ADDOP(c, YIELD_FROM);
4066 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004067 case Await_kind:
4068 if (c->u->u_ste->ste_type != FunctionBlock)
4069 return compiler_error(c, "'await' outside function");
4070
Yury Selivanov9dec0352015-06-30 12:49:04 -04004071 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
4072 return compiler_error(
4073 c, "'await' expressions in comprehensions are not supported");
4074
Yury Selivanov75445082015-05-11 22:57:16 -04004075 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
4076 return compiler_error(c, "'await' outside async function");
4077
4078 VISIT(c, expr, e->v.Await.value);
4079 ADDOP(c, GET_AWAITABLE);
4080 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4081 ADDOP(c, YIELD_FROM);
4082 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 case Compare_kind:
4084 return compiler_compare(c, e);
4085 case Call_kind:
4086 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004087 case Constant_kind:
4088 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4089 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 case Num_kind:
4091 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4092 break;
4093 case Str_kind:
4094 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4095 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004096 case JoinedStr_kind:
4097 return compiler_joined_str(c, e);
4098 case FormattedValue_kind:
4099 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 case Bytes_kind:
4101 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4102 break;
4103 case Ellipsis_kind:
4104 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4105 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004106 case NameConstant_kind:
4107 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4108 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 /* The following exprs can be assignment targets. */
4110 case Attribute_kind:
4111 if (e->v.Attribute.ctx != AugStore)
4112 VISIT(c, expr, e->v.Attribute.value);
4113 switch (e->v.Attribute.ctx) {
4114 case AugLoad:
4115 ADDOP(c, DUP_TOP);
4116 /* Fall through to load */
4117 case Load:
4118 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4119 break;
4120 case AugStore:
4121 ADDOP(c, ROT_TWO);
4122 /* Fall through to save */
4123 case Store:
4124 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4125 break;
4126 case Del:
4127 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4128 break;
4129 case Param:
4130 default:
4131 PyErr_SetString(PyExc_SystemError,
4132 "param invalid in attribute expression");
4133 return 0;
4134 }
4135 break;
4136 case Subscript_kind:
4137 switch (e->v.Subscript.ctx) {
4138 case AugLoad:
4139 VISIT(c, expr, e->v.Subscript.value);
4140 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4141 break;
4142 case Load:
4143 VISIT(c, expr, e->v.Subscript.value);
4144 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4145 break;
4146 case AugStore:
4147 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4148 break;
4149 case Store:
4150 VISIT(c, expr, e->v.Subscript.value);
4151 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4152 break;
4153 case Del:
4154 VISIT(c, expr, e->v.Subscript.value);
4155 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4156 break;
4157 case Param:
4158 default:
4159 PyErr_SetString(PyExc_SystemError,
4160 "param invalid in subscript expression");
4161 return 0;
4162 }
4163 break;
4164 case Starred_kind:
4165 switch (e->v.Starred.ctx) {
4166 case Store:
4167 /* In all legitimate cases, the Starred node was already replaced
4168 * by compiler_list/compiler_tuple. XXX: is that okay? */
4169 return compiler_error(c,
4170 "starred assignment target must be in a list or tuple");
4171 default:
4172 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004173 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 }
4175 break;
4176 case Name_kind:
4177 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4178 /* child nodes of List and Tuple will have expr_context set */
4179 case List_kind:
4180 return compiler_list(c, e);
4181 case Tuple_kind:
4182 return compiler_tuple(c, e);
4183 }
4184 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004185}
4186
4187static int
4188compiler_augassign(struct compiler *c, stmt_ty s)
4189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 expr_ty e = s->v.AugAssign.target;
4191 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 switch (e->kind) {
4196 case Attribute_kind:
4197 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4198 AugLoad, e->lineno, e->col_offset, c->c_arena);
4199 if (auge == NULL)
4200 return 0;
4201 VISIT(c, expr, auge);
4202 VISIT(c, expr, s->v.AugAssign.value);
4203 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4204 auge->v.Attribute.ctx = AugStore;
4205 VISIT(c, expr, auge);
4206 break;
4207 case Subscript_kind:
4208 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4209 AugLoad, e->lineno, e->col_offset, c->c_arena);
4210 if (auge == NULL)
4211 return 0;
4212 VISIT(c, expr, auge);
4213 VISIT(c, expr, s->v.AugAssign.value);
4214 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4215 auge->v.Subscript.ctx = AugStore;
4216 VISIT(c, expr, auge);
4217 break;
4218 case Name_kind:
4219 if (!compiler_nameop(c, e->v.Name.id, Load))
4220 return 0;
4221 VISIT(c, expr, s->v.AugAssign.value);
4222 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4223 return compiler_nameop(c, e->v.Name.id, Store);
4224 default:
4225 PyErr_Format(PyExc_SystemError,
4226 "invalid node type (%d) for augmented assignment",
4227 e->kind);
4228 return 0;
4229 }
4230 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004231}
4232
4233static int
4234compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 struct fblockinfo *f;
4237 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4238 PyErr_SetString(PyExc_SystemError,
4239 "too many statically nested blocks");
4240 return 0;
4241 }
4242 f = &c->u->u_fblock[c->u->u_nfblocks++];
4243 f->fb_type = t;
4244 f->fb_block = b;
4245 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246}
4247
4248static void
4249compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 struct compiler_unit *u = c->u;
4252 assert(u->u_nfblocks > 0);
4253 u->u_nfblocks--;
4254 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4255 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004256}
4257
Thomas Wouters89f507f2006-12-13 04:49:30 +00004258static int
4259compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 int i;
4261 struct compiler_unit *u = c->u;
4262 for (i = 0; i < u->u_nfblocks; ++i) {
4263 if (u->u_fblock[i].fb_type == LOOP)
4264 return 1;
4265 }
4266 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004267}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268/* Raises a SyntaxError and returns 0.
4269 If something goes wrong, a different exception may be raised.
4270*/
4271
4272static int
4273compiler_error(struct compiler *c, const char *errstr)
4274{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004275 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277
Victor Stinner14e461d2013-08-26 22:28:21 +02004278 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 if (!loc) {
4280 Py_INCREF(Py_None);
4281 loc = Py_None;
4282 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004283 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004284 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 if (!u)
4286 goto exit;
4287 v = Py_BuildValue("(zO)", errstr, u);
4288 if (!v)
4289 goto exit;
4290 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 Py_DECREF(loc);
4293 Py_XDECREF(u);
4294 Py_XDECREF(v);
4295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296}
4297
4298static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299compiler_handle_subscr(struct compiler *c, const char *kind,
4300 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 /* XXX this code is duplicated */
4305 switch (ctx) {
4306 case AugLoad: /* fall through to Load */
4307 case Load: op = BINARY_SUBSCR; break;
4308 case AugStore:/* fall through to Store */
4309 case Store: op = STORE_SUBSCR; break;
4310 case Del: op = DELETE_SUBSCR; break;
4311 case Param:
4312 PyErr_Format(PyExc_SystemError,
4313 "invalid %s kind %d in subscript\n",
4314 kind, ctx);
4315 return 0;
4316 }
4317 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004318 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 }
4320 else if (ctx == AugStore) {
4321 ADDOP(c, ROT_THREE);
4322 }
4323 ADDOP(c, op);
4324 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325}
4326
4327static int
4328compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 int n = 2;
4331 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 /* only handles the cases where BUILD_SLICE is emitted */
4334 if (s->v.Slice.lower) {
4335 VISIT(c, expr, s->v.Slice.lower);
4336 }
4337 else {
4338 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 if (s->v.Slice.upper) {
4342 VISIT(c, expr, s->v.Slice.upper);
4343 }
4344 else {
4345 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4346 }
4347
4348 if (s->v.Slice.step) {
4349 n++;
4350 VISIT(c, expr, s->v.Slice.step);
4351 }
4352 ADDOP_I(c, BUILD_SLICE, n);
4353 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354}
4355
4356static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4358 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 switch (s->kind) {
4361 case Slice_kind:
4362 return compiler_slice(c, s, ctx);
4363 case Index_kind:
4364 VISIT(c, expr, s->v.Index.value);
4365 break;
4366 case ExtSlice_kind:
4367 default:
4368 PyErr_SetString(PyExc_SystemError,
4369 "extended slice invalid in nested slice");
4370 return 0;
4371 }
4372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373}
4374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375static int
4376compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 char * kindname = NULL;
4379 switch (s->kind) {
4380 case Index_kind:
4381 kindname = "index";
4382 if (ctx != AugStore) {
4383 VISIT(c, expr, s->v.Index.value);
4384 }
4385 break;
4386 case Slice_kind:
4387 kindname = "slice";
4388 if (ctx != AugStore) {
4389 if (!compiler_slice(c, s, ctx))
4390 return 0;
4391 }
4392 break;
4393 case ExtSlice_kind:
4394 kindname = "extended slice";
4395 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004396 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 for (i = 0; i < n; i++) {
4398 slice_ty sub = (slice_ty)asdl_seq_GET(
4399 s->v.ExtSlice.dims, i);
4400 if (!compiler_visit_nested_slice(c, sub, ctx))
4401 return 0;
4402 }
4403 ADDOP_I(c, BUILD_TUPLE, n);
4404 }
4405 break;
4406 default:
4407 PyErr_Format(PyExc_SystemError,
4408 "invalid subscript kind %d", s->kind);
4409 return 0;
4410 }
4411 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004412}
4413
Thomas Wouters89f507f2006-12-13 04:49:30 +00004414/* End of the compiler section, beginning of the assembler section */
4415
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416/* do depth-first search of basic block graph, starting with block.
4417 post records the block indices in post-order.
4418
4419 XXX must handle implicit jumps from one block to next
4420*/
4421
Thomas Wouters89f507f2006-12-13 04:49:30 +00004422struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 PyObject *a_bytecode; /* string containing bytecode */
4424 int a_offset; /* offset into bytecode */
4425 int a_nblocks; /* number of reachable blocks */
4426 basicblock **a_postorder; /* list of blocks in dfs postorder */
4427 PyObject *a_lnotab; /* string containing lnotab */
4428 int a_lnotab_off; /* offset into lnotab */
4429 int a_lineno; /* last lineno of emitted instruction */
4430 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004431};
4432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433static void
4434dfs(struct compiler *c, basicblock *b, struct assembler *a)
4435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 int i;
4437 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if (b->b_seen)
4440 return;
4441 b->b_seen = 1;
4442 if (b->b_next != NULL)
4443 dfs(c, b->b_next, a);
4444 for (i = 0; i < b->b_iused; i++) {
4445 instr = &b->b_instr[i];
4446 if (instr->i_jrel || instr->i_jabs)
4447 dfs(c, instr->i_target, a);
4448 }
4449 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004450}
4451
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004452static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004453stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4454{
Larry Hastings3a907972013-11-23 14:49:22 -08004455 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 struct instr *instr;
4457 if (b->b_seen || b->b_startdepth >= depth)
4458 return maxdepth;
4459 b->b_seen = 1;
4460 b->b_startdepth = depth;
4461 for (i = 0; i < b->b_iused; i++) {
4462 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004463 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4464 if (effect == PY_INVALID_STACK_EFFECT) {
4465 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4466 Py_FatalError("PyCompile_OpcodeStackEffect()");
4467 }
4468 depth += effect;
4469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 if (depth > maxdepth)
4471 maxdepth = depth;
4472 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4473 if (instr->i_jrel || instr->i_jabs) {
4474 target_depth = depth;
4475 if (instr->i_opcode == FOR_ITER) {
4476 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004477 }
4478 else if (instr->i_opcode == SETUP_FINALLY ||
4479 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 target_depth = depth+3;
4481 if (target_depth > maxdepth)
4482 maxdepth = target_depth;
4483 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004484 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4485 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4486 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 maxdepth = stackdepth_walk(c, instr->i_target,
4488 target_depth, maxdepth);
4489 if (instr->i_opcode == JUMP_ABSOLUTE ||
4490 instr->i_opcode == JUMP_FORWARD) {
4491 goto out; /* remaining code is dead */
4492 }
4493 }
4494 }
4495 if (b->b_next)
4496 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004497out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 b->b_seen = 0;
4499 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
4502/* Find the flow path that needs the largest stack. We assume that
4503 * cycles in the flow graph have no net effect on the stack depth.
4504 */
4505static int
4506stackdepth(struct compiler *c)
4507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 basicblock *b, *entryblock;
4509 entryblock = NULL;
4510 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4511 b->b_seen = 0;
4512 b->b_startdepth = INT_MIN;
4513 entryblock = b;
4514 }
4515 if (!entryblock)
4516 return 0;
4517 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004518}
4519
4520static int
4521assemble_init(struct assembler *a, int nblocks, int firstlineno)
4522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 memset(a, 0, sizeof(struct assembler));
4524 a->a_lineno = firstlineno;
4525 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4526 if (!a->a_bytecode)
4527 return 0;
4528 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4529 if (!a->a_lnotab)
4530 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004531 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 PyErr_NoMemory();
4533 return 0;
4534 }
4535 a->a_postorder = (basicblock **)PyObject_Malloc(
4536 sizeof(basicblock *) * nblocks);
4537 if (!a->a_postorder) {
4538 PyErr_NoMemory();
4539 return 0;
4540 }
4541 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542}
4543
4544static void
4545assemble_free(struct assembler *a)
4546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 Py_XDECREF(a->a_bytecode);
4548 Py_XDECREF(a->a_lnotab);
4549 if (a->a_postorder)
4550 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004551}
4552
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553static int
4554blocksize(basicblock *b)
4555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 int i;
4557 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004560 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004562}
4563
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004564/* Appends a pair to the end of the line number table, a_lnotab, representing
4565 the instruction's bytecode offset and line number. See
4566 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004567
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004568static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004569assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004572 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 d_bytecode = a->a_offset - a->a_lineno_off;
4576 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 if(d_bytecode == 0 && d_lineno == 0)
4581 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (d_bytecode > 255) {
4584 int j, nbytes, ncodes = d_bytecode / 255;
4585 nbytes = a->a_lnotab_off + 2 * ncodes;
4586 len = PyBytes_GET_SIZE(a->a_lnotab);
4587 if (nbytes >= len) {
4588 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4589 len = nbytes;
4590 else if (len <= INT_MAX / 2)
4591 len *= 2;
4592 else {
4593 PyErr_NoMemory();
4594 return 0;
4595 }
4596 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4597 return 0;
4598 }
4599 lnotab = (unsigned char *)
4600 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4601 for (j = 0; j < ncodes; j++) {
4602 *lnotab++ = 255;
4603 *lnotab++ = 0;
4604 }
4605 d_bytecode -= ncodes * 255;
4606 a->a_lnotab_off += ncodes * 2;
4607 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004608 assert(0 <= d_bytecode && d_bytecode <= 255);
4609
4610 if (d_lineno < -128 || 127 < d_lineno) {
4611 int j, nbytes, ncodes, k;
4612 if (d_lineno < 0) {
4613 k = -128;
4614 /* use division on positive numbers */
4615 ncodes = (-d_lineno) / 128;
4616 }
4617 else {
4618 k = 127;
4619 ncodes = d_lineno / 127;
4620 }
4621 d_lineno -= ncodes * k;
4622 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 nbytes = a->a_lnotab_off + 2 * ncodes;
4624 len = PyBytes_GET_SIZE(a->a_lnotab);
4625 if (nbytes >= len) {
4626 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4627 len = nbytes;
4628 else if (len <= INT_MAX / 2)
4629 len *= 2;
4630 else {
4631 PyErr_NoMemory();
4632 return 0;
4633 }
4634 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4635 return 0;
4636 }
4637 lnotab = (unsigned char *)
4638 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4639 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004640 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 d_bytecode = 0;
4642 for (j = 1; j < ncodes; j++) {
4643 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004644 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 a->a_lnotab_off += ncodes * 2;
4647 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004648 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 len = PyBytes_GET_SIZE(a->a_lnotab);
4651 if (a->a_lnotab_off + 2 >= len) {
4652 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4653 return 0;
4654 }
4655 lnotab = (unsigned char *)
4656 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 a->a_lnotab_off += 2;
4659 if (d_bytecode) {
4660 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004661 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 }
4663 else { /* First line of a block; def stmt, etc. */
4664 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004665 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 }
4667 a->a_lineno = i->i_lineno;
4668 a->a_lineno_off = a->a_offset;
4669 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004670}
4671
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004672/* assemble_emit()
4673 Extend the bytecode with a new instruction.
4674 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004675*/
4676
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004677static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004678assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004679{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004680 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4682 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004683
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004684 arg = i->i_oparg;
4685 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 if (i->i_lineno && !assemble_lnotab(a, i))
4687 return 0;
4688 if (a->a_offset + size >= len) {
4689 if (len > PY_SSIZE_T_MAX / 2)
4690 return 0;
4691 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4692 return 0;
4693 }
4694 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4695 a->a_offset += size;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004696 write_op_arg((unsigned char*)code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004698}
4699
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004700static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004701assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004704 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 /* Compute the size of each block and fixup jump args.
4708 Replace block pointer with position in bytecode. */
4709 do {
4710 totsize = 0;
4711 for (i = a->a_nblocks - 1; i >= 0; i--) {
4712 b = a->a_postorder[i];
4713 bsize = blocksize(b);
4714 b->b_offset = totsize;
4715 totsize += bsize;
4716 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004717 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4719 bsize = b->b_offset;
4720 for (i = 0; i < b->b_iused; i++) {
4721 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004722 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 /* Relative jumps are computed relative to
4724 the instruction pointer after fetching
4725 the jump instruction.
4726 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004727 bsize += isize;
4728 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004730 if (instr->i_jrel) {
4731 instr->i_oparg -= bsize;
4732 }
4733 if (instrsize(instr->i_oparg) != isize) {
4734 extended_arg_recompile = 1;
4735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 }
4738 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 /* XXX: This is an awful hack that could hurt performance, but
4741 on the bright side it should work until we come up
4742 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 The issue is that in the first loop blocksize() is called
4745 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004746 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 So we loop until we stop seeing new EXTENDED_ARGs.
4750 The only EXTENDED_ARGs that could be popping up are
4751 ones in jump instructions. So this should converge
4752 fairly quickly.
4753 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004754 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004755}
4756
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004757static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004758dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 PyObject *tuple, *k, *v;
4761 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 tuple = PyTuple_New(size);
4764 if (tuple == NULL)
4765 return NULL;
4766 while (PyDict_Next(dict, &pos, &k, &v)) {
4767 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004768 /* The keys of the dictionary are tuples. (see compiler_add_o
4769 * and _PyCode_ConstantKey). The object we want is always second,
4770 * though. */
4771 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 Py_INCREF(k);
4773 assert((i - offset) < size);
4774 assert((i - offset) >= 0);
4775 PyTuple_SET_ITEM(tuple, i - offset, k);
4776 }
4777 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004778}
4779
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004780static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004781compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004784 int flags = 0;
4785 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004787 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (ste->ste_nested)
4789 flags |= CO_NESTED;
4790 if (ste->ste_generator)
4791 flags |= CO_GENERATOR;
4792 if (ste->ste_varargs)
4793 flags |= CO_VARARGS;
4794 if (ste->ste_varkeywords)
4795 flags |= CO_VARKEYWORDS;
4796 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 /* (Only) inherit compilerflags in PyCF_MASK */
4799 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 n = PyDict_Size(c->u->u_freevars);
4802 if (n < 0)
4803 return -1;
4804 if (n == 0) {
4805 n = PyDict_Size(c->u->u_cellvars);
4806 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004807 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004809 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 }
4811 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004814}
4815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004816static PyCodeObject *
4817makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 PyObject *tmp;
4820 PyCodeObject *co = NULL;
4821 PyObject *consts = NULL;
4822 PyObject *names = NULL;
4823 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 PyObject *name = NULL;
4825 PyObject *freevars = NULL;
4826 PyObject *cellvars = NULL;
4827 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004828 Py_ssize_t nlocals;
4829 int nlocals_int;
4830 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004831 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 tmp = dict_keys_inorder(c->u->u_consts, 0);
4834 if (!tmp)
4835 goto error;
4836 consts = PySequence_List(tmp); /* optimize_code requires a list */
4837 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 names = dict_keys_inorder(c->u->u_names, 0);
4840 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4841 if (!consts || !names || !varnames)
4842 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4845 if (!cellvars)
4846 goto error;
4847 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4848 if (!freevars)
4849 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004852 assert(nlocals < INT_MAX);
4853 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 flags = compute_code_flags(c);
4856 if (flags < 0)
4857 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4860 if (!bytecode)
4861 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4864 if (!tmp)
4865 goto error;
4866 Py_DECREF(consts);
4867 consts = tmp;
4868
Victor Stinnerf8e32212013-11-19 23:56:34 +01004869 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4870 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4871 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004872 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 bytecode, consts, names, varnames,
4874 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004875 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 c->u->u_firstlineno,
4877 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004878 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 Py_XDECREF(consts);
4880 Py_XDECREF(names);
4881 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 Py_XDECREF(name);
4883 Py_XDECREF(freevars);
4884 Py_XDECREF(cellvars);
4885 Py_XDECREF(bytecode);
4886 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004887}
4888
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004889
4890/* For debugging purposes only */
4891#if 0
4892static void
4893dump_instr(const struct instr *i)
4894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 const char *jrel = i->i_jrel ? "jrel " : "";
4896 const char *jabs = i->i_jabs ? "jabs " : "";
4897 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004900 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004902 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4904 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004905}
4906
4907static void
4908dump_basicblock(const basicblock *b)
4909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 const char *seen = b->b_seen ? "seen " : "";
4911 const char *b_return = b->b_return ? "return " : "";
4912 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4913 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4914 if (b->b_instr) {
4915 int i;
4916 for (i = 0; i < b->b_iused; i++) {
4917 fprintf(stderr, " [%02d] ", i);
4918 dump_instr(b->b_instr + i);
4919 }
4920 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004921}
4922#endif
4923
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004924static PyCodeObject *
4925assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 basicblock *b, *entryblock;
4928 struct assembler a;
4929 int i, j, nblocks;
4930 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 /* Make sure every block that falls off the end returns None.
4933 XXX NEXT_BLOCK() isn't quite right, because if the last
4934 block ends with a jump or return b_next shouldn't set.
4935 */
4936 if (!c->u->u_curblock->b_return) {
4937 NEXT_BLOCK(c);
4938 if (addNone)
4939 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4940 ADDOP(c, RETURN_VALUE);
4941 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 nblocks = 0;
4944 entryblock = NULL;
4945 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4946 nblocks++;
4947 entryblock = b;
4948 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 /* Set firstlineno if it wasn't explicitly set. */
4951 if (!c->u->u_firstlineno) {
4952 if (entryblock && entryblock->b_instr)
4953 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4954 else
4955 c->u->u_firstlineno = 1;
4956 }
4957 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4958 goto error;
4959 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 /* Can't modify the bytecode after computing jump offsets. */
4962 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 /* Emit code in reverse postorder from dfs. */
4965 for (i = a.a_nblocks - 1; i >= 0; i--) {
4966 b = a.a_postorder[i];
4967 for (j = 0; j < b->b_iused; j++)
4968 if (!assemble_emit(&a, &b->b_instr[j]))
4969 goto error;
4970 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4973 goto error;
4974 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4975 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 assemble_free(&a);
4980 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004981}
Georg Brandl8334fd92010-12-04 10:26:46 +00004982
4983#undef PyAST_Compile
4984PyAPI_FUNC(PyCodeObject *)
4985PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4986 PyArena *arena)
4987{
4988 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4989}