blob: dad7404a85f3f4f25a48142951d73b7320db4d39 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (c.c_st == NULL) {
336 if (!PyErr_Occurred())
337 PyErr_SetString(PyExc_SystemError, "no symtable");
338 goto finally;
339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Thomas Wouters1175c432006-02-27 22:49:54 +0000343 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 compiler_free(&c);
345 assert(co || PyErr_Occurred());
346 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347}
348
349PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200350PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
351 int optimize, PyArena *arena)
352{
353 PyObject *filename;
354 PyCodeObject *co;
355 filename = PyUnicode_DecodeFSDefault(filename_str);
356 if (filename == NULL)
357 return NULL;
358 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
359 Py_DECREF(filename);
360 return co;
361
362}
363
364PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365PyNode_Compile(struct _node *n, const char *filename)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyCodeObject *co = NULL;
368 mod_ty mod;
369 PyArena *arena = PyArena_New();
370 if (!arena)
371 return NULL;
372 mod = PyAST_FromNode(n, NULL, filename, arena);
373 if (mod)
374 co = PyAST_Compile(mod, filename, NULL, arena);
375 PyArena_Free(arena);
376 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000377}
378
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (c->c_st)
383 PySymtable_Free(c->c_st);
384 if (c->c_future)
385 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000388}
389
Guido van Rossum79f25d91997-04-29 20:08:16 +0000390static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t i, n;
394 PyObject *v, *k;
395 PyObject *dict = PyDict_New();
396 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 n = PyList_Size(list);
399 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100400 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (!v) {
402 Py_DECREF(dict);
403 return NULL;
404 }
405 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100406 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
408 Py_XDECREF(k);
409 Py_DECREF(v);
410 Py_DECREF(dict);
411 return NULL;
412 }
413 Py_DECREF(k);
414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100462 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100469 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
474 Py_XDECREF(tuple);
475 return NULL;
476 }
477 Py_DECREF(item);
478 Py_DECREF(tuple);
479 }
480 }
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000483}
484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485static void
486compiler_unit_check(struct compiler_unit *u)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 basicblock *block;
489 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700490 assert((uintptr_t)block != 0xcbcbcbcbU);
491 assert((uintptr_t)block != 0xfbfbfbfbU);
492 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (block->b_instr != NULL) {
494 assert(block->b_ialloc > 0);
495 assert(block->b_iused > 0);
496 assert(block->b_ialloc >= block->b_iused);
497 }
498 else {
499 assert (block->b_iused == 0);
500 assert (block->b_ialloc == 0);
501 }
502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503}
504
505static void
506compiler_unit_free(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 compiler_unit_check(u);
511 b = u->u_blocks;
512 while (b != NULL) {
513 if (b->b_instr)
514 PyObject_Free((void *)b->b_instr);
515 next = b->b_list;
516 PyObject_Free((void *)b);
517 b = next;
518 }
519 Py_CLEAR(u->u_ste);
520 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400521 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_CLEAR(u->u_consts);
523 Py_CLEAR(u->u_names);
524 Py_CLEAR(u->u_varnames);
525 Py_CLEAR(u->u_freevars);
526 Py_CLEAR(u->u_cellvars);
527 Py_CLEAR(u->u_private);
528 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100532compiler_enter_scope(struct compiler *c, identifier name,
533 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100536 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
539 struct compiler_unit));
540 if (!u) {
541 PyErr_NoMemory();
542 return 0;
543 }
544 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100545 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_argcount = 0;
547 u->u_kwonlyargcount = 0;
548 u->u_ste = PySymtable_Lookup(c->c_st, key);
549 if (!u->u_ste) {
550 compiler_unit_free(u);
551 return 0;
552 }
553 Py_INCREF(name);
554 u->u_name = name;
555 u->u_varnames = list2dict(u->u_ste->ste_varnames);
556 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
557 if (!u->u_varnames || !u->u_cellvars) {
558 compiler_unit_free(u);
559 return 0;
560 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000562 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300564 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 int res;
566 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200567 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 name = _PyUnicode_FromId(&PyId___class__);
569 if (!name) {
570 compiler_unit_free(u);
571 return 0;
572 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100573 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 if (!tuple) {
575 compiler_unit_free(u);
576 return 0;
577 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300578 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (res < 0) {
581 compiler_unit_free(u);
582 return 0;
583 }
584 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200587 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (!u->u_freevars) {
589 compiler_unit_free(u);
590 return 0;
591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_blocks = NULL;
594 u->u_nfblocks = 0;
595 u->u_firstlineno = lineno;
596 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000597 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 u->u_lineno_set = 0;
599 u->u_consts = PyDict_New();
600 if (!u->u_consts) {
601 compiler_unit_free(u);
602 return 0;
603 }
604 u->u_names = PyDict_New();
605 if (!u->u_names) {
606 compiler_unit_free(u);
607 return 0;
608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Push the old compiler_unit on the stack. */
613 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400614 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
616 Py_XDECREF(capsule);
617 compiler_unit_free(u);
618 return 0;
619 }
620 Py_DECREF(capsule);
621 u->u_private = c->u->u_private;
622 Py_XINCREF(u->u_private);
623 }
624 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627
628 block = compiler_new_block(c);
629 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400633 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
634 if (!compiler_set_qualname(c))
635 return 0;
636 }
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642compiler_exit_scope(struct compiler *c)
643{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100644 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel--;
648 compiler_unit_free(c->u);
649 /* Restore c->u to the parent unit. */
650 n = PyList_GET_SIZE(c->c_stack) - 1;
651 if (n >= 0) {
652 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400653 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(c->u);
655 /* we are deleting from a list so this really shouldn't fail */
656 if (PySequence_DelItem(c->c_stack, n) < 0)
657 Py_FatalError("compiler_exit_scope()");
658 compiler_unit_check(c->u);
659 }
660 else
661 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663}
664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665static int
666compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 _Py_static_string(dot_locals, ".<locals>");
670 Py_ssize_t stack_size;
671 struct compiler_unit *u = c->u;
672 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400676 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 if (stack_size > 1) {
678 int scope, force_global = 0;
679 struct compiler_unit *parent;
680 PyObject *mangled, *capsule;
681
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400682 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 assert(parent);
685
Yury Selivanov75445082015-05-11 22:57:16 -0400686 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
687 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 assert(u->u_name);
690 mangled = _Py_Mangle(parent->u_private, u->u_name);
691 if (!mangled)
692 return 0;
693 scope = PyST_GetScope(parent->u_ste, mangled);
694 Py_DECREF(mangled);
695 assert(scope != GLOBAL_IMPLICIT);
696 if (scope == GLOBAL_EXPLICIT)
697 force_global = 1;
698 }
699
700 if (!force_global) {
701 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400702 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
704 dot_locals_str = _PyUnicode_FromId(&dot_locals);
705 if (dot_locals_str == NULL)
706 return 0;
707 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
708 if (base == NULL)
709 return 0;
710 }
711 else {
712 Py_INCREF(parent->u_qualname);
713 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100715 }
716 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400717
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 if (base != NULL) {
719 dot_str = _PyUnicode_FromId(&dot);
720 if (dot_str == NULL) {
721 Py_DECREF(base);
722 return 0;
723 }
724 name = PyUnicode_Concat(base, dot_str);
725 Py_DECREF(base);
726 if (name == NULL)
727 return 0;
728 PyUnicode_Append(&name, u->u_name);
729 if (name == NULL)
730 return 0;
731 }
732 else {
733 Py_INCREF(u->u_name);
734 name = u->u_name;
735 }
736 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739}
740
Eric V. Smith235a6f02015-09-19 14:51:32 -0400741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742/* Allocate a new block and return a pointer to it.
743 Returns NULL on error.
744*/
745
746static basicblock *
747compiler_new_block(struct compiler *c)
748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 basicblock *b;
750 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 u = c->u;
753 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
754 if (b == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 memset((void *)b, 0, sizeof(basicblock));
759 /* Extend the singly linked list of blocks with new block. */
760 b->b_list = u->u_blocks;
761 u->u_blocks = b;
762 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700811 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
Larry Hastings3a907972013-11-23 14:49:22 -0800856int
857PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400884 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_MODULO:
886 case BINARY_ADD:
887 case BINARY_SUBTRACT:
888 case BINARY_SUBSCR:
889 case BINARY_FLOOR_DIVIDE:
890 case BINARY_TRUE_DIVIDE:
891 return -1;
892 case INPLACE_FLOOR_DIVIDE:
893 case INPLACE_TRUE_DIVIDE:
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_ADD:
897 case INPLACE_SUBTRACT:
898 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400899 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_MODULO:
901 return -1;
902 case STORE_SUBSCR:
903 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400932 case WITH_CLEANUP_START:
933 return 1;
934 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case RETURN_VALUE:
937 return -1;
938 case IMPORT_STAR:
939 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700940 case SETUP_ANNOTATIONS:
941 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300979 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300983 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400984 case BUILD_SET_UNPACK:
985 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400986 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700987 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300990 case BUILD_CONST_KEY_MAP:
991 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case LOAD_ATTR:
993 return 0;
994 case COMPARE_OP:
995 return -1;
996 case IMPORT_NAME:
997 return -1;
998 case IMPORT_FROM:
999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case JUMP_FORWARD:
1002 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1003 case JUMP_IF_FALSE_OR_POP: /* "" */
1004 case JUMP_ABSOLUTE:
1005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case POP_JUMP_IF_FALSE:
1008 case POP_JUMP_IF_TRUE:
1009 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_GLOBAL:
1012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case CONTINUE_LOOP:
1015 return 0;
1016 case SETUP_LOOP:
1017 return 0;
1018 case SETUP_EXCEPT:
1019 case SETUP_FINALLY:
1020 return 6; /* can push 3 values for the new exception
1021 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case LOAD_FAST:
1024 return 1;
1025 case STORE_FAST:
1026 return -1;
1027 case DELETE_FAST:
1028 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001029 case STORE_ANNOTATION:
1030 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case RAISE_VARARGS:
1033 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001035 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001036 case CALL_METHOD:
1037 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg-1;
1040 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001041 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001042 case MAKE_FUNCTION:
1043 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1044 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case BUILD_SLICE:
1046 if (oparg == 3)
1047 return -2;
1048 else
1049 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case LOAD_CLOSURE:
1052 return 1;
1053 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001054 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 1;
1056 case STORE_DEREF:
1057 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001058 case DELETE_DEREF:
1059 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001060 case GET_AWAITABLE:
1061 return 0;
1062 case SETUP_ASYNC_WITH:
1063 return 6;
1064 case BEFORE_ASYNC_WITH:
1065 return 1;
1066 case GET_AITER:
1067 return 0;
1068 case GET_ANEXT:
1069 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001070 case GET_YIELD_FROM_ITER:
1071 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001072 case FORMAT_VALUE:
1073 /* If there's a fmt_spec on the stack, we go from 2->1,
1074 else 1->1. */
1075 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001076 case LOAD_METHOD:
1077 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001079 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Larry Hastings3a907972013-11-23 14:49:22 -08001081 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082}
1083
1084/* Add an opcode with no argument.
1085 Returns 0 on failure, 1 on success.
1086*/
1087
1088static int
1089compiler_addop(struct compiler *c, int opcode)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 basicblock *b;
1092 struct instr *i;
1093 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001094 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 off = compiler_next_instr(c, c->u->u_curblock);
1096 if (off < 0)
1097 return 0;
1098 b = c->u->u_curblock;
1099 i = &b->b_instr[off];
1100 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (opcode == RETURN_VALUE)
1103 b->b_return = 1;
1104 compiler_set_lineno(c, off);
1105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106}
1107
Victor Stinnerf8e32212013-11-19 23:56:34 +01001108static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *t, *v;
1112 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Victor Stinnerefb24132016-01-22 12:33:12 +01001114 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (t == NULL)
1116 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 v = PyDict_GetItem(dict, t);
1119 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001120 if (PyErr_Occurred()) {
1121 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001123 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001124 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001125 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!v) {
1127 Py_DECREF(t);
1128 return -1;
1129 }
1130 if (PyDict_SetItem(dict, t, v) < 0) {
1131 Py_DECREF(t);
1132 Py_DECREF(v);
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 }
1137 else
1138 arg = PyLong_AsLong(v);
1139 Py_DECREF(t);
1140 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
1143static int
1144compiler_addop_o(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 = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001149 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return compiler_addop_i(c, opcode, arg);
1151}
1152
1153static int
1154compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001157 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1159 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 arg = compiler_add_o(c, dict, mangled);
1162 Py_DECREF(mangled);
1163 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return compiler_addop_i(c, opcode, arg);
1166}
1167
1168/* Add an opcode with an integer argument.
1169 Returns 0 on failure, 1 on success.
1170*/
1171
1172static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 struct instr *i;
1176 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Victor Stinner2ad474b2016-03-01 23:34:47 +01001178 /* oparg value is unsigned, but a signed C int is usually used to store
1179 it in the C code (like Python/ceval.c).
1180
1181 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1182
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 The argument of a concrete bytecode instruction is limited to 8-bit.
1184 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1185 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001186 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 off = compiler_next_instr(c, c->u->u_curblock);
1189 if (off < 0)
1190 return 0;
1191 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001192 i->i_opcode = opcode;
1193 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001204 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 assert(b != NULL);
1206 off = compiler_next_instr(c, c->u->u_curblock);
1207 if (off < 0)
1208 return 0;
1209 i = &c->u->u_curblock->b_instr[off];
1210 i->i_opcode = opcode;
1211 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001220/* NEXT_BLOCK() creates an implicit jump from the current block
1221 to the new block.
1222
1223 The returns inside this macro make it impossible to decref objects
1224 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (compiler_next_block((C)) == NULL) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop((C), (OP))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001236#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop((C), (OP))) { \
1238 compiler_exit_scope(c); \
1239 return 0; \
1240 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001241}
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001248/* Same as ADDOP_O, but steals a reference. */
1249#define ADDOP_N(C, OP, O, TYPE) { \
1250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1251 Py_DECREF((O)); \
1252 return 0; \
1253 } \
1254 Py_DECREF((O)); \
1255}
1256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_i((C), (OP), (O))) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop_j((C), (OP), (O), 1)) \
1269 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
1272#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_addop_j((C), (OP), (O), 0)) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
1277/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1278 the ASDL name to synthesize the name of the C type and the visit function.
1279*/
1280
1281#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_visit_ ## TYPE((C), (V))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_visit_ ## TYPE((C), (V))) { \
1288 compiler_exit_scope(c); \
1289 return 0; \
1290 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001291}
1292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_slice((C), (V), (CTX))) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298#define VISIT_SEQ(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 return 0; \
1305 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 int _i; \
1310 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1311 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1312 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1313 if (!compiler_visit_ ## TYPE((C), elt)) { \
1314 compiler_exit_scope(c); \
1315 return 0; \
1316 } \
1317 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001318}
1319
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001321is_const(expr_ty e)
1322{
1323 switch (e->kind) {
1324 case Constant_kind:
1325 case Num_kind:
1326 case Str_kind:
1327 case Bytes_kind:
1328 case Ellipsis_kind:
1329 case NameConstant_kind:
1330 return 1;
1331 default:
1332 return 0;
1333 }
1334}
1335
1336static PyObject *
1337get_const_value(expr_ty e)
1338{
1339 switch (e->kind) {
1340 case Constant_kind:
1341 return e->v.Constant.value;
1342 case Num_kind:
1343 return e->v.Num.n;
1344 case Str_kind:
1345 return e->v.Str.s;
1346 case Bytes_kind:
1347 return e->v.Bytes.s;
1348 case Ellipsis_kind:
1349 return Py_Ellipsis;
1350 case NameConstant_kind:
1351 return e->v.NameConstant.value;
1352 default:
1353 assert(!is_const(e));
1354 return NULL;
1355 }
1356}
1357
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001358/* Search if variable annotations are present statically in a block. */
1359
1360static int
1361find_ann(asdl_seq *stmts)
1362{
1363 int i, j, res = 0;
1364 stmt_ty st;
1365
1366 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1367 st = (stmt_ty)asdl_seq_GET(stmts, i);
1368 switch (st->kind) {
1369 case AnnAssign_kind:
1370 return 1;
1371 case For_kind:
1372 res = find_ann(st->v.For.body) ||
1373 find_ann(st->v.For.orelse);
1374 break;
1375 case AsyncFor_kind:
1376 res = find_ann(st->v.AsyncFor.body) ||
1377 find_ann(st->v.AsyncFor.orelse);
1378 break;
1379 case While_kind:
1380 res = find_ann(st->v.While.body) ||
1381 find_ann(st->v.While.orelse);
1382 break;
1383 case If_kind:
1384 res = find_ann(st->v.If.body) ||
1385 find_ann(st->v.If.orelse);
1386 break;
1387 case With_kind:
1388 res = find_ann(st->v.With.body);
1389 break;
1390 case AsyncWith_kind:
1391 res = find_ann(st->v.AsyncWith.body);
1392 break;
1393 case Try_kind:
1394 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1395 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1396 st->v.Try.handlers, j);
1397 if (find_ann(handler->v.ExceptHandler.body)) {
1398 return 1;
1399 }
1400 }
1401 res = find_ann(st->v.Try.body) ||
1402 find_ann(st->v.Try.finalbody) ||
1403 find_ann(st->v.Try.orelse);
1404 break;
1405 default:
1406 res = 0;
1407 }
1408 if (res) {
1409 break;
1410 }
1411 }
1412 return res;
1413}
1414
1415/* Compile a sequence of statements, checking for a docstring
1416 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
1418static int
INADA Naokicb41b272017-02-23 00:31:59 +09001419compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001421 /* Set current line number to the line number of first statement.
1422 This way line number for SETUP_ANNOTATIONS will always
1423 coincide with the line number of first "real" statement in module.
1424 If body is empy, then lineno will be set later in assemble. */
1425 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1426 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001427 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001428 c->u->u_lineno = st->lineno;
1429 }
1430 /* Every annotated class and module should have __annotations__. */
1431 if (find_ann(stmts)) {
1432 ADDOP(c, SETUP_ANNOTATIONS);
1433 }
INADA Naokicb41b272017-02-23 00:31:59 +09001434 /* if not -OO mode, set docstring */
1435 if (c->c_optimize < 2 && docstring) {
1436 ADDOP_O(c, LOAD_CONST, docstring, consts);
1437 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
INADA Naokicb41b272017-02-23 00:31:59 +09001439 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441}
1442
1443static PyCodeObject *
1444compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyCodeObject *co;
1447 int addNone = 1;
1448 static PyObject *module;
1449 if (!module) {
1450 module = PyUnicode_InternFromString("<module>");
1451 if (!module)
1452 return NULL;
1453 }
1454 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001455 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return NULL;
1457 switch (mod->kind) {
1458 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001459 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 compiler_exit_scope(c);
1461 return 0;
1462 }
1463 break;
1464 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001465 if (find_ann(mod->v.Interactive.body)) {
1466 ADDOP(c, SETUP_ANNOTATIONS);
1467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 c->c_interactive = 1;
1469 VISIT_SEQ_IN_SCOPE(c, stmt,
1470 mod->v.Interactive.body);
1471 break;
1472 case Expression_kind:
1473 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1474 addNone = 0;
1475 break;
1476 case Suite_kind:
1477 PyErr_SetString(PyExc_SystemError,
1478 "suite should not be possible");
1479 return 0;
1480 default:
1481 PyErr_Format(PyExc_SystemError,
1482 "module kind %d should not be possible",
1483 mod->kind);
1484 return 0;
1485 }
1486 co = assemble(c, addNone);
1487 compiler_exit_scope(c);
1488 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001489}
1490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491/* The test for LOCAL must come before the test for FREE in order to
1492 handle classes where name is both local and free. The local var is
1493 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001494*/
1495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496static int
1497get_ref_type(struct compiler *c, PyObject *name)
1498{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001499 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001500 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001501 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001502 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001503 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (scope == 0) {
1505 char buf[350];
1506 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001507 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001509 PyUnicode_AsUTF8(name),
1510 PyUnicode_AsUTF8(c->u->u_name),
1511 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1512 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1513 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1514 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 );
1516 Py_FatalError(buf);
1517 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
1522static int
1523compiler_lookup_arg(PyObject *dict, PyObject *name)
1524{
1525 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001526 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001528 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001530 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001532 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001533 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001537compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001539 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001540 if (qualname == NULL)
1541 qualname = co->co_name;
1542
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001543 if (free) {
1544 for (i = 0; i < free; ++i) {
1545 /* Bypass com_addop_varname because it will generate
1546 LOAD_DEREF but LOAD_CLOSURE is needed.
1547 */
1548 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1549 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001551 /* Special case: If a class contains a method with a
1552 free variable that has the same name as a method,
1553 the name will be considered free *and* local in the
1554 class. It should be handled by the closure, as
1555 well as by the normal name loookup logic.
1556 */
1557 reftype = get_ref_type(c, name);
1558 if (reftype == CELL)
1559 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1560 else /* (reftype == FREE) */
1561 arg = compiler_lookup_arg(c->u->u_freevars, name);
1562 if (arg == -1) {
1563 fprintf(stderr,
1564 "lookup %s in %s %d %d\n"
1565 "freevars of %s: %s\n",
1566 PyUnicode_AsUTF8(PyObject_Repr(name)),
1567 PyUnicode_AsUTF8(c->u->u_name),
1568 reftype, arg,
1569 PyUnicode_AsUTF8(co->co_name),
1570 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1571 Py_FatalError("compiler_make_closure()");
1572 }
1573 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001575 flags |= 0x08;
1576 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001579 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001580 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582}
1583
1584static int
1585compiler_decorators(struct compiler *c, asdl_seq* decos)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (!decos)
1590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1593 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1594 }
1595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596}
1597
1598static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001599compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001601{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001602 /* Push a dict of keyword-only default values.
1603
1604 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1605 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001606 int i;
1607 PyObject *keys = NULL;
1608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1610 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1611 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1612 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001613 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001614 if (!mangled) {
1615 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001617 if (keys == NULL) {
1618 keys = PyList_New(1);
1619 if (keys == NULL) {
1620 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001621 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001622 }
1623 PyList_SET_ITEM(keys, 0, mangled);
1624 }
1625 else {
1626 int res = PyList_Append(keys, mangled);
1627 Py_DECREF(mangled);
1628 if (res == -1) {
1629 goto error;
1630 }
1631 }
1632 if (!compiler_visit_expr(c, default_)) {
1633 goto error;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 }
1636 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001637 if (keys != NULL) {
1638 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1639 PyObject *keys_tuple = PyList_AsTuple(keys);
1640 Py_DECREF(keys);
1641 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001642 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001643 }
1644 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1645 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001646 assert(default_count > 0);
1647 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001648 }
1649 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001650 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001651 }
1652
1653error:
1654 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001655 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001656}
1657
1658static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001659compiler_visit_argannotation(struct compiler *c, identifier id,
1660 expr_ty annotation, PyObject *names)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001663 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001665 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001666 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001667 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001668 if (PyList_Append(names, mangled) < 0) {
1669 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001670 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001671 }
1672 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001674 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001675}
1676
1677static int
1678compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1679 PyObject *names)
1680{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001681 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 for (i = 0; i < asdl_seq_LEN(args); i++) {
1683 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001684 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 c,
1686 arg->arg,
1687 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001688 names))
1689 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001692}
1693
1694static int
1695compiler_visit_annotations(struct compiler *c, arguments_ty args,
1696 expr_ty returns)
1697{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001698 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001699 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001700
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001701 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 */
1703 static identifier return_str;
1704 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001705 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 names = PyList_New(0);
1707 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001708 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001709
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001710 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001712 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001713 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001714 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001716 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001718 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001719 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001720 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (!return_str) {
1724 return_str = PyUnicode_InternFromString("return");
1725 if (!return_str)
1726 goto error;
1727 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001728 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 goto error;
1730 }
1731
1732 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001734 PyObject *keytuple = PyList_AsTuple(names);
1735 Py_DECREF(names);
1736 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001737 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001739 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1740 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001741 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001743 else {
1744 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001745 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001746 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001747
1748error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001750 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001751}
1752
1753static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001754compiler_visit_defaults(struct compiler *c, arguments_ty args)
1755{
1756 VISIT_SEQ(c, expr, args->defaults);
1757 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759}
1760
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761static Py_ssize_t
1762compiler_default_arguments(struct compiler *c, arguments_ty args)
1763{
1764 Py_ssize_t funcflags = 0;
1765 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001766 if (!compiler_visit_defaults(c, args))
1767 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 funcflags |= 0x01;
1769 }
1770 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001772 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001773 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001774 return -1;
1775 }
1776 else if (res > 0) {
1777 funcflags |= 0x02;
1778 }
1779 }
1780 return funcflags;
1781}
1782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783static int
Yury Selivanov75445082015-05-11 22:57:16 -04001784compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001787 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001788 arguments_ty args;
1789 expr_ty returns;
1790 identifier name;
1791 asdl_seq* decos;
1792 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001793 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001795 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796
Yury Selivanov75445082015-05-11 22:57:16 -04001797 if (is_async) {
1798 assert(s->kind == AsyncFunctionDef_kind);
1799
1800 args = s->v.AsyncFunctionDef.args;
1801 returns = s->v.AsyncFunctionDef.returns;
1802 decos = s->v.AsyncFunctionDef.decorator_list;
1803 name = s->v.AsyncFunctionDef.name;
1804 body = s->v.AsyncFunctionDef.body;
1805
1806 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1807 } else {
1808 assert(s->kind == FunctionDef_kind);
1809
1810 args = s->v.FunctionDef.args;
1811 returns = s->v.FunctionDef.returns;
1812 decos = s->v.FunctionDef.decorator_list;
1813 name = s->v.FunctionDef.name;
1814 body = s->v.FunctionDef.body;
1815
1816 scope_type = COMPILER_SCOPE_FUNCTION;
1817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (!compiler_decorators(c, decos))
1820 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001821
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822 funcflags = compiler_default_arguments(c, args);
1823 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001825 }
1826
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001827 annotations = compiler_visit_annotations(c, args, returns);
1828 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 return 0;
1830 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001831 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001832 funcflags |= 0x04;
1833 }
1834
1835 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1836 return 0;
1837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838
INADA Naokicb41b272017-02-23 00:31:59 +09001839 /* if not -OO mode, add docstring */
1840 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1841 docstring = s->v.FunctionDef.docstring;
1842 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 compiler_exit_scope(c);
1844 return 0;
1845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->u->u_argcount = asdl_seq_LEN(args->args);
1848 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001850 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001852 qualname = c->u->u_qualname;
1853 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001855 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001856 Py_XDECREF(qualname);
1857 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001861 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* decorators */
1866 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1867 ADDOP_I(c, CALL_FUNCTION, 1);
1868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Yury Selivanov75445082015-05-11 22:57:16 -04001870 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871}
1872
1873static int
1874compiler_class(struct compiler *c, stmt_ty s)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyCodeObject *co;
1877 PyObject *str;
1878 int i;
1879 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!compiler_decorators(c, decos))
1882 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* ultimately generate code for:
1885 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1886 where:
1887 <func> is a function/closure created from the class body;
1888 it has a single argument (__locals__) where the dict
1889 (or MutableSequence) representing the locals is passed
1890 <name> is the class name
1891 <bases> is the positional arguments and *varargs argument
1892 <keywords> is the keyword arguments and **kwds argument
1893 This borrows from compiler_call.
1894 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001897 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1898 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 return 0;
1900 /* this block represents what we do in the new scope */
1901 {
1902 /* use the class name for name mangling */
1903 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001904 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* load (global) __name__ ... */
1906 str = PyUnicode_InternFromString("__name__");
1907 if (!str || !compiler_nameop(c, str, Load)) {
1908 Py_XDECREF(str);
1909 compiler_exit_scope(c);
1910 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_DECREF(str);
1913 /* ... and store it as __module__ */
1914 str = PyUnicode_InternFromString("__module__");
1915 if (!str || !compiler_nameop(c, str, Store)) {
1916 Py_XDECREF(str);
1917 compiler_exit_scope(c);
1918 return 0;
1919 }
1920 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001921 assert(c->u->u_qualname);
1922 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 str = PyUnicode_InternFromString("__qualname__");
1924 if (!str || !compiler_nameop(c, str, Store)) {
1925 Py_XDECREF(str);
1926 compiler_exit_scope(c);
1927 return 0;
1928 }
1929 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001931 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 compiler_exit_scope(c);
1933 return 0;
1934 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001935 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001936 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001937 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001938 str = PyUnicode_InternFromString("__class__");
1939 if (str == NULL) {
1940 compiler_exit_scope(c);
1941 return 0;
1942 }
1943 i = compiler_lookup_arg(c->u->u_cellvars, str);
1944 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001945 if (i < 0) {
1946 compiler_exit_scope(c);
1947 return 0;
1948 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001949 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001952 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001953 str = PyUnicode_InternFromString("__classcell__");
1954 if (!str || !compiler_nameop(c, str, Store)) {
1955 Py_XDECREF(str);
1956 compiler_exit_scope(c);
1957 return 0;
1958 }
1959 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001961 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001962 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001963 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001964 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001965 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001966 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* create the code object */
1968 co = assemble(c, 1);
1969 }
1970 /* leave the new scope */
1971 compiler_exit_scope(c);
1972 if (co == NULL)
1973 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* 2. load the 'build_class' function */
1976 ADDOP(c, LOAD_BUILD_CLASS);
1977
1978 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001979 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Py_DECREF(co);
1981
1982 /* 4. load class name */
1983 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1984
1985 /* 5. generate the rest of the code for the call */
1986 if (!compiler_call_helper(c, 2,
1987 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001988 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 0;
1990
1991 /* 6. apply decorators */
1992 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1993 ADDOP_I(c, CALL_FUNCTION, 1);
1994 }
1995
1996 /* 7. store into <name> */
1997 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1998 return 0;
1999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000}
2001
2002static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002003compiler_ifexp(struct compiler *c, expr_ty e)
2004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 basicblock *end, *next;
2006
2007 assert(e->kind == IfExp_kind);
2008 end = compiler_new_block(c);
2009 if (end == NULL)
2010 return 0;
2011 next = compiler_new_block(c);
2012 if (next == NULL)
2013 return 0;
2014 VISIT(c, expr, e->v.IfExp.test);
2015 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2016 VISIT(c, expr, e->v.IfExp.body);
2017 ADDOP_JREL(c, JUMP_FORWARD, end);
2018 compiler_use_next_block(c, next);
2019 VISIT(c, expr, e->v.IfExp.orelse);
2020 compiler_use_next_block(c, end);
2021 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002022}
2023
2024static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025compiler_lambda(struct compiler *c, expr_ty e)
2026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002028 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 arguments_ty args = e->v.Lambda.args;
2032 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (!name) {
2035 name = PyUnicode_InternFromString("<lambda>");
2036 if (!name)
2037 return 0;
2038 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002040 funcflags = compiler_default_arguments(c, args);
2041 if (funcflags == -1) {
2042 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002044
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002045 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002046 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Make None the first constant, so the lambda can't have a
2050 docstring. */
2051 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2052 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 c->u->u_argcount = asdl_seq_LEN(args->args);
2055 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2056 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2057 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002058 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
2060 else {
2061 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002062 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002064 qualname = c->u->u_qualname;
2065 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002067 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002070 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002071 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 Py_DECREF(co);
2073
2074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075}
2076
2077static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078compiler_if(struct compiler *c, stmt_ty s)
2079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 basicblock *end, *next;
2081 int constant;
2082 assert(s->kind == If_kind);
2083 end = compiler_new_block(c);
2084 if (end == NULL)
2085 return 0;
2086
Georg Brandl8334fd92010-12-04 10:26:46 +00002087 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* constant = 0: "if 0"
2089 * constant = 1: "if 1", "if 2", ...
2090 * constant = -1: rest */
2091 if (constant == 0) {
2092 if (s->v.If.orelse)
2093 VISIT_SEQ(c, stmt, s->v.If.orelse);
2094 } else if (constant == 1) {
2095 VISIT_SEQ(c, stmt, s->v.If.body);
2096 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002097 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 next = compiler_new_block(c);
2099 if (next == NULL)
2100 return 0;
2101 }
2102 else
2103 next = end;
2104 VISIT(c, expr, s->v.If.test);
2105 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2106 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002107 if (asdl_seq_LEN(s->v.If.orelse)) {
2108 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 compiler_use_next_block(c, next);
2110 VISIT_SEQ(c, stmt, s->v.If.orelse);
2111 }
2112 }
2113 compiler_use_next_block(c, end);
2114 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115}
2116
2117static int
2118compiler_for(struct compiler *c, stmt_ty s)
2119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 start = compiler_new_block(c);
2123 cleanup = compiler_new_block(c);
2124 end = compiler_new_block(c);
2125 if (start == NULL || end == NULL || cleanup == NULL)
2126 return 0;
2127 ADDOP_JREL(c, SETUP_LOOP, end);
2128 if (!compiler_push_fblock(c, LOOP, start))
2129 return 0;
2130 VISIT(c, expr, s->v.For.iter);
2131 ADDOP(c, GET_ITER);
2132 compiler_use_next_block(c, start);
2133 ADDOP_JREL(c, FOR_ITER, cleanup);
2134 VISIT(c, expr, s->v.For.target);
2135 VISIT_SEQ(c, stmt, s->v.For.body);
2136 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2137 compiler_use_next_block(c, cleanup);
2138 ADDOP(c, POP_BLOCK);
2139 compiler_pop_fblock(c, LOOP, start);
2140 VISIT_SEQ(c, stmt, s->v.For.orelse);
2141 compiler_use_next_block(c, end);
2142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143}
2144
Yury Selivanov75445082015-05-11 22:57:16 -04002145
2146static int
2147compiler_async_for(struct compiler *c, stmt_ty s)
2148{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002149 _Py_IDENTIFIER(StopAsyncIteration);
2150
Yury Selivanov75445082015-05-11 22:57:16 -04002151 basicblock *try, *except, *end, *after_try, *try_cleanup,
2152 *after_loop, *after_loop_else;
2153
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002154 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2155 if (stop_aiter_error == NULL) {
2156 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002157 }
2158
2159 try = compiler_new_block(c);
2160 except = compiler_new_block(c);
2161 end = compiler_new_block(c);
2162 after_try = compiler_new_block(c);
2163 try_cleanup = compiler_new_block(c);
2164 after_loop = compiler_new_block(c);
2165 after_loop_else = compiler_new_block(c);
2166
2167 if (try == NULL || except == NULL || end == NULL
2168 || after_try == NULL || try_cleanup == NULL)
2169 return 0;
2170
2171 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2172 if (!compiler_push_fblock(c, LOOP, try))
2173 return 0;
2174
2175 VISIT(c, expr, s->v.AsyncFor.iter);
2176 ADDOP(c, GET_AITER);
2177 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2178 ADDOP(c, YIELD_FROM);
2179
2180 compiler_use_next_block(c, try);
2181
2182
2183 ADDOP_JREL(c, SETUP_EXCEPT, except);
2184 if (!compiler_push_fblock(c, EXCEPT, try))
2185 return 0;
2186
2187 ADDOP(c, GET_ANEXT);
2188 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2189 ADDOP(c, YIELD_FROM);
2190 VISIT(c, expr, s->v.AsyncFor.target);
2191 ADDOP(c, POP_BLOCK);
2192 compiler_pop_fblock(c, EXCEPT, try);
2193 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2194
2195
2196 compiler_use_next_block(c, except);
2197 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002198 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002199 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2200 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2201
2202 ADDOP(c, POP_TOP);
2203 ADDOP(c, POP_TOP);
2204 ADDOP(c, POP_TOP);
2205 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2206 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2207 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2208
2209
2210 compiler_use_next_block(c, try_cleanup);
2211 ADDOP(c, END_FINALLY);
2212
2213 compiler_use_next_block(c, after_try);
2214 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2215 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2216
2217 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2218 compiler_pop_fblock(c, LOOP, try);
2219
2220 compiler_use_next_block(c, after_loop);
2221 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2222
2223 compiler_use_next_block(c, after_loop_else);
2224 VISIT_SEQ(c, stmt, s->v.For.orelse);
2225
2226 compiler_use_next_block(c, end);
2227
2228 return 1;
2229}
2230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231static int
2232compiler_while(struct compiler *c, stmt_ty s)
2233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002235 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (constant == 0) {
2238 if (s->v.While.orelse)
2239 VISIT_SEQ(c, stmt, s->v.While.orelse);
2240 return 1;
2241 }
2242 loop = compiler_new_block(c);
2243 end = compiler_new_block(c);
2244 if (constant == -1) {
2245 anchor = compiler_new_block(c);
2246 if (anchor == NULL)
2247 return 0;
2248 }
2249 if (loop == NULL || end == NULL)
2250 return 0;
2251 if (s->v.While.orelse) {
2252 orelse = compiler_new_block(c);
2253 if (orelse == NULL)
2254 return 0;
2255 }
2256 else
2257 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 ADDOP_JREL(c, SETUP_LOOP, end);
2260 compiler_use_next_block(c, loop);
2261 if (!compiler_push_fblock(c, LOOP, loop))
2262 return 0;
2263 if (constant == -1) {
2264 VISIT(c, expr, s->v.While.test);
2265 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2266 }
2267 VISIT_SEQ(c, stmt, s->v.While.body);
2268 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 /* XXX should the two POP instructions be in a separate block
2271 if there is no else clause ?
2272 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002274 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002276 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 compiler_pop_fblock(c, LOOP, loop);
2278 if (orelse != NULL) /* what if orelse is just pass? */
2279 VISIT_SEQ(c, stmt, s->v.While.orelse);
2280 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283}
2284
2285static int
2286compiler_continue(struct compiler *c)
2287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2289 static const char IN_FINALLY_ERROR_MSG[] =
2290 "'continue' not supported inside 'finally' clause";
2291 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (!c->u->u_nfblocks)
2294 return compiler_error(c, LOOP_ERROR_MSG);
2295 i = c->u->u_nfblocks - 1;
2296 switch (c->u->u_fblock[i].fb_type) {
2297 case LOOP:
2298 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2299 break;
2300 case EXCEPT:
2301 case FINALLY_TRY:
2302 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2303 /* Prevent continue anywhere under a finally
2304 even if hidden in a sub-try or except. */
2305 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2306 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2307 }
2308 if (i == -1)
2309 return compiler_error(c, LOOP_ERROR_MSG);
2310 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2311 break;
2312 case FINALLY_END:
2313 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317}
2318
2319/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320
2321 SETUP_FINALLY L
2322 <code for body>
2323 POP_BLOCK
2324 LOAD_CONST <None>
2325 L: <code for finalbody>
2326 END_FINALLY
2327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 The special instructions use the block stack. Each block
2329 stack entry contains the instruction that created it (here
2330 SETUP_FINALLY), the level of the value stack at the time the
2331 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 Pushes the current value stack level and the label
2335 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 Pops en entry from the block stack, and pops the value
2338 stack until its level is the same as indicated on the
2339 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 Pops a variable number of entries from the *value* stack
2342 and re-raises the exception they specify. The number of
2343 entries popped depends on the (pseudo) exception type.
2344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 The block stack is unwound when an exception is raised:
2346 when a SETUP_FINALLY entry is found, the exception is pushed
2347 onto the value stack (and the exception condition is cleared),
2348 and the interpreter jumps to the label gotten from the block
2349 stack.
2350*/
2351
2352static int
2353compiler_try_finally(struct compiler *c, stmt_ty s)
2354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 basicblock *body, *end;
2356 body = compiler_new_block(c);
2357 end = compiler_new_block(c);
2358 if (body == NULL || end == NULL)
2359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 ADDOP_JREL(c, SETUP_FINALLY, end);
2362 compiler_use_next_block(c, body);
2363 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2364 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002365 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2366 if (!compiler_try_except(c, s))
2367 return 0;
2368 }
2369 else {
2370 VISIT_SEQ(c, stmt, s->v.Try.body);
2371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 ADDOP(c, POP_BLOCK);
2373 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2376 compiler_use_next_block(c, end);
2377 if (!compiler_push_fblock(c, FINALLY_END, end))
2378 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002379 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 ADDOP(c, END_FINALLY);
2381 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384}
2385
2386/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002387 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388 (The contents of the value stack is shown in [], with the top
2389 at the right; 'tb' is trace-back info, 'val' the exception's
2390 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391
2392 Value stack Label Instruction Argument
2393 [] SETUP_EXCEPT L1
2394 [] <code for S>
2395 [] POP_BLOCK
2396 [] JUMP_FORWARD L0
2397
2398 [tb, val, exc] L1: DUP )
2399 [tb, val, exc, exc] <evaluate E1> )
2400 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2401 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2402 [tb, val, exc] POP
2403 [tb, val] <assign to V1> (or POP if no V1)
2404 [tb] POP
2405 [] <code for S1>
2406 JUMP_FORWARD L0
2407
2408 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409 .............................etc.......................
2410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2412
2413 [] L0: <next statement>
2414
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 Of course, parts are not generated if Vi or Ei is not present.
2416*/
2417static int
2418compiler_try_except(struct compiler *c, stmt_ty s)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002421 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 body = compiler_new_block(c);
2424 except = compiler_new_block(c);
2425 orelse = compiler_new_block(c);
2426 end = compiler_new_block(c);
2427 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2428 return 0;
2429 ADDOP_JREL(c, SETUP_EXCEPT, except);
2430 compiler_use_next_block(c, body);
2431 if (!compiler_push_fblock(c, EXCEPT, body))
2432 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002433 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 ADDOP(c, POP_BLOCK);
2435 compiler_pop_fblock(c, EXCEPT, body);
2436 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002437 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 compiler_use_next_block(c, except);
2439 for (i = 0; i < n; i++) {
2440 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002441 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 if (!handler->v.ExceptHandler.type && i < n-1)
2443 return compiler_error(c, "default 'except:' must be last");
2444 c->u->u_lineno_set = 0;
2445 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002446 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 except = compiler_new_block(c);
2448 if (except == NULL)
2449 return 0;
2450 if (handler->v.ExceptHandler.type) {
2451 ADDOP(c, DUP_TOP);
2452 VISIT(c, expr, handler->v.ExceptHandler.type);
2453 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2454 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2455 }
2456 ADDOP(c, POP_TOP);
2457 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002458 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002459
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002460 cleanup_end = compiler_new_block(c);
2461 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002462 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002463 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002464
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002465 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2466 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002468 /*
2469 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002470 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002471 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002472 try:
2473 # body
2474 finally:
2475 name = None
2476 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002477 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002479 /* second try: */
2480 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2481 compiler_use_next_block(c, cleanup_body);
2482 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2483 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002485 /* second # body */
2486 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2487 ADDOP(c, POP_BLOCK);
2488 ADDOP(c, POP_EXCEPT);
2489 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002491 /* finally: */
2492 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2493 compiler_use_next_block(c, cleanup_end);
2494 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2495 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002497 /* name = None */
2498 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2499 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002501 /* del name */
2502 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002504 ADDOP(c, END_FINALLY);
2505 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 }
2507 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002508 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002510 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002511 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002512 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513
Guido van Rossumb940e112007-01-10 16:19:56 +00002514 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002515 ADDOP(c, POP_TOP);
2516 compiler_use_next_block(c, cleanup_body);
2517 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2518 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002520 ADDOP(c, POP_EXCEPT);
2521 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 }
2523 ADDOP_JREL(c, JUMP_FORWARD, end);
2524 compiler_use_next_block(c, except);
2525 }
2526 ADDOP(c, END_FINALLY);
2527 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002528 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 compiler_use_next_block(c, end);
2530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531}
2532
2533static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002534compiler_try(struct compiler *c, stmt_ty s) {
2535 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2536 return compiler_try_finally(c, s);
2537 else
2538 return compiler_try_except(c, s);
2539}
2540
2541
2542static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543compiler_import_as(struct compiler *c, identifier name, identifier asname)
2544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* The IMPORT_NAME opcode was already generated. This function
2546 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002549 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2552 PyUnicode_GET_LENGTH(name), 1);
2553 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002554 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002557 Py_ssize_t pos = dot + 1;
2558 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 dot = PyUnicode_FindChar(name, '.', pos,
2561 PyUnicode_GET_LENGTH(name), 1);
2562 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002563 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 attr = PyUnicode_Substring(name, pos,
2565 (dot != -1) ? dot :
2566 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002568 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002569 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002571 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 }
2573 }
2574 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575}
2576
2577static int
2578compiler_import(struct compiler *c, stmt_ty s)
2579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* The Import node stores a module name like a.b.c as a single
2581 string. This is convenient for all cases except
2582 import a.b.c as d
2583 where we need to parse that string to extract the individual
2584 module names.
2585 XXX Perhaps change the representation to make this case simpler?
2586 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002587 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 for (i = 0; i < n; i++) {
2590 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2591 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002593 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2595 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 if (alias->asname) {
2598 r = compiler_import_as(c, alias->name, alias->asname);
2599 if (!r)
2600 return r;
2601 }
2602 else {
2603 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 Py_ssize_t dot = PyUnicode_FindChar(
2605 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002606 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002608 if (tmp == NULL)
2609 return 0;
2610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002612 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 Py_DECREF(tmp);
2614 }
2615 if (!r)
2616 return r;
2617 }
2618 }
2619 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620}
2621
2622static int
2623compiler_from_import(struct compiler *c, stmt_ty s)
2624{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002625 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyObject *names = PyTuple_New(n);
2628 PyObject *level;
2629 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (!empty_string) {
2632 empty_string = PyUnicode_FromString("");
2633 if (!empty_string)
2634 return 0;
2635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (!names)
2638 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 level = PyLong_FromLong(s->v.ImportFrom.level);
2641 if (!level) {
2642 Py_DECREF(names);
2643 return 0;
2644 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 /* build up the names */
2647 for (i = 0; i < n; i++) {
2648 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2649 Py_INCREF(alias->name);
2650 PyTuple_SET_ITEM(names, i, alias->name);
2651 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002654 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 Py_DECREF(level);
2656 Py_DECREF(names);
2657 return compiler_error(c, "from __future__ imports must occur "
2658 "at the beginning of the file");
2659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 ADDOP_O(c, LOAD_CONST, level, consts);
2662 Py_DECREF(level);
2663 ADDOP_O(c, LOAD_CONST, names, consts);
2664 Py_DECREF(names);
2665 if (s->v.ImportFrom.module) {
2666 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2667 }
2668 else {
2669 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2670 }
2671 for (i = 0; i < n; i++) {
2672 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2673 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002675 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 assert(n == 1);
2677 ADDOP(c, IMPORT_STAR);
2678 return 1;
2679 }
2680
2681 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2682 store_name = alias->name;
2683 if (alias->asname)
2684 store_name = alias->asname;
2685
2686 if (!compiler_nameop(c, store_name, Store)) {
2687 Py_DECREF(names);
2688 return 0;
2689 }
2690 }
2691 /* remove imported module */
2692 ADDOP(c, POP_TOP);
2693 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694}
2695
2696static int
2697compiler_assert(struct compiler *c, stmt_ty s)
2698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 static PyObject *assertion_error = NULL;
2700 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002701 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Georg Brandl8334fd92010-12-04 10:26:46 +00002703 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return 1;
2705 if (assertion_error == NULL) {
2706 assertion_error = PyUnicode_InternFromString("AssertionError");
2707 if (assertion_error == NULL)
2708 return 0;
2709 }
2710 if (s->v.Assert.test->kind == Tuple_kind &&
2711 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002712 msg = PyUnicode_FromString("assertion is always true, "
2713 "perhaps remove parentheses?");
2714 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002716 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2717 c->c_filename, c->u->u_lineno,
2718 NULL, NULL) == -1) {
2719 Py_DECREF(msg);
2720 return 0;
2721 }
2722 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 }
2724 VISIT(c, expr, s->v.Assert.test);
2725 end = compiler_new_block(c);
2726 if (end == NULL)
2727 return 0;
2728 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2729 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2730 if (s->v.Assert.msg) {
2731 VISIT(c, expr, s->v.Assert.msg);
2732 ADDOP_I(c, CALL_FUNCTION, 1);
2733 }
2734 ADDOP_I(c, RAISE_VARARGS, 1);
2735 compiler_use_next_block(c, end);
2736 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737}
2738
2739static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002740compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2741{
2742 if (c->c_interactive && c->c_nestlevel <= 1) {
2743 VISIT(c, expr, value);
2744 ADDOP(c, PRINT_EXPR);
2745 return 1;
2746 }
2747
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002748 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002749 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002750 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002751 }
2752
2753 VISIT(c, expr, value);
2754 ADDOP(c, POP_TOP);
2755 return 1;
2756}
2757
2758static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759compiler_visit_stmt(struct compiler *c, stmt_ty s)
2760{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002761 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 /* Always assign a lineno to the next instruction for a stmt. */
2764 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002765 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 switch (s->kind) {
2769 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002770 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 case ClassDef_kind:
2772 return compiler_class(c, s);
2773 case Return_kind:
2774 if (c->u->u_ste->ste_type != FunctionBlock)
2775 return compiler_error(c, "'return' outside function");
2776 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002777 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2778 return compiler_error(
2779 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 VISIT(c, expr, s->v.Return.value);
2781 }
2782 else
2783 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2784 ADDOP(c, RETURN_VALUE);
2785 break;
2786 case Delete_kind:
2787 VISIT_SEQ(c, expr, s->v.Delete.targets)
2788 break;
2789 case Assign_kind:
2790 n = asdl_seq_LEN(s->v.Assign.targets);
2791 VISIT(c, expr, s->v.Assign.value);
2792 for (i = 0; i < n; i++) {
2793 if (i < n - 1)
2794 ADDOP(c, DUP_TOP);
2795 VISIT(c, expr,
2796 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2797 }
2798 break;
2799 case AugAssign_kind:
2800 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002801 case AnnAssign_kind:
2802 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 case For_kind:
2804 return compiler_for(c, s);
2805 case While_kind:
2806 return compiler_while(c, s);
2807 case If_kind:
2808 return compiler_if(c, s);
2809 case Raise_kind:
2810 n = 0;
2811 if (s->v.Raise.exc) {
2812 VISIT(c, expr, s->v.Raise.exc);
2813 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002814 if (s->v.Raise.cause) {
2815 VISIT(c, expr, s->v.Raise.cause);
2816 n++;
2817 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002819 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002821 case Try_kind:
2822 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 case Assert_kind:
2824 return compiler_assert(c, s);
2825 case Import_kind:
2826 return compiler_import(c, s);
2827 case ImportFrom_kind:
2828 return compiler_from_import(c, s);
2829 case Global_kind:
2830 case Nonlocal_kind:
2831 break;
2832 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002833 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 case Pass_kind:
2835 break;
2836 case Break_kind:
2837 if (!compiler_in_loop(c))
2838 return compiler_error(c, "'break' outside loop");
2839 ADDOP(c, BREAK_LOOP);
2840 break;
2841 case Continue_kind:
2842 return compiler_continue(c);
2843 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002844 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002845 case AsyncFunctionDef_kind:
2846 return compiler_function(c, s, 1);
2847 case AsyncWith_kind:
2848 return compiler_async_with(c, s, 0);
2849 case AsyncFor_kind:
2850 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
Yury Selivanov75445082015-05-11 22:57:16 -04002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854}
2855
2856static int
2857unaryop(unaryop_ty op)
2858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 switch (op) {
2860 case Invert:
2861 return UNARY_INVERT;
2862 case Not:
2863 return UNARY_NOT;
2864 case UAdd:
2865 return UNARY_POSITIVE;
2866 case USub:
2867 return UNARY_NEGATIVE;
2868 default:
2869 PyErr_Format(PyExc_SystemError,
2870 "unary op %d should not be possible", op);
2871 return 0;
2872 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873}
2874
2875static int
2876binop(struct compiler *c, operator_ty op)
2877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 switch (op) {
2879 case Add:
2880 return BINARY_ADD;
2881 case Sub:
2882 return BINARY_SUBTRACT;
2883 case Mult:
2884 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002885 case MatMult:
2886 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 case Div:
2888 return BINARY_TRUE_DIVIDE;
2889 case Mod:
2890 return BINARY_MODULO;
2891 case Pow:
2892 return BINARY_POWER;
2893 case LShift:
2894 return BINARY_LSHIFT;
2895 case RShift:
2896 return BINARY_RSHIFT;
2897 case BitOr:
2898 return BINARY_OR;
2899 case BitXor:
2900 return BINARY_XOR;
2901 case BitAnd:
2902 return BINARY_AND;
2903 case FloorDiv:
2904 return BINARY_FLOOR_DIVIDE;
2905 default:
2906 PyErr_Format(PyExc_SystemError,
2907 "binary op %d should not be possible", op);
2908 return 0;
2909 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910}
2911
2912static int
2913cmpop(cmpop_ty op)
2914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 switch (op) {
2916 case Eq:
2917 return PyCmp_EQ;
2918 case NotEq:
2919 return PyCmp_NE;
2920 case Lt:
2921 return PyCmp_LT;
2922 case LtE:
2923 return PyCmp_LE;
2924 case Gt:
2925 return PyCmp_GT;
2926 case GtE:
2927 return PyCmp_GE;
2928 case Is:
2929 return PyCmp_IS;
2930 case IsNot:
2931 return PyCmp_IS_NOT;
2932 case In:
2933 return PyCmp_IN;
2934 case NotIn:
2935 return PyCmp_NOT_IN;
2936 default:
2937 return PyCmp_BAD;
2938 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939}
2940
2941static int
2942inplace_binop(struct compiler *c, operator_ty op)
2943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 switch (op) {
2945 case Add:
2946 return INPLACE_ADD;
2947 case Sub:
2948 return INPLACE_SUBTRACT;
2949 case Mult:
2950 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002951 case MatMult:
2952 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 case Div:
2954 return INPLACE_TRUE_DIVIDE;
2955 case Mod:
2956 return INPLACE_MODULO;
2957 case Pow:
2958 return INPLACE_POWER;
2959 case LShift:
2960 return INPLACE_LSHIFT;
2961 case RShift:
2962 return INPLACE_RSHIFT;
2963 case BitOr:
2964 return INPLACE_OR;
2965 case BitXor:
2966 return INPLACE_XOR;
2967 case BitAnd:
2968 return INPLACE_AND;
2969 case FloorDiv:
2970 return INPLACE_FLOOR_DIVIDE;
2971 default:
2972 PyErr_Format(PyExc_SystemError,
2973 "inplace binary op %d should not be possible", op);
2974 return 0;
2975 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976}
2977
2978static int
2979compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2980{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002981 int op, scope;
2982 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 PyObject *dict = c->u->u_names;
2986 PyObject *mangled;
2987 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 mangled = _Py_Mangle(c->u->u_private, name);
2990 if (!mangled)
2991 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002992
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002993 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
2994 !_PyUnicode_EqualToASCIIString(name, "True") &&
2995 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 op = 0;
2998 optype = OP_NAME;
2999 scope = PyST_GetScope(c->u->u_ste, mangled);
3000 switch (scope) {
3001 case FREE:
3002 dict = c->u->u_freevars;
3003 optype = OP_DEREF;
3004 break;
3005 case CELL:
3006 dict = c->u->u_cellvars;
3007 optype = OP_DEREF;
3008 break;
3009 case LOCAL:
3010 if (c->u->u_ste->ste_type == FunctionBlock)
3011 optype = OP_FAST;
3012 break;
3013 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003014 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 optype = OP_GLOBAL;
3016 break;
3017 case GLOBAL_EXPLICIT:
3018 optype = OP_GLOBAL;
3019 break;
3020 default:
3021 /* scope can be 0 */
3022 break;
3023 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003026 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 switch (optype) {
3029 case OP_DEREF:
3030 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003031 case Load:
3032 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3033 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 case Store: op = STORE_DEREF; break;
3035 case AugLoad:
3036 case AugStore:
3037 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003038 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 case Param:
3040 default:
3041 PyErr_SetString(PyExc_SystemError,
3042 "param invalid for deref variable");
3043 return 0;
3044 }
3045 break;
3046 case OP_FAST:
3047 switch (ctx) {
3048 case Load: op = LOAD_FAST; break;
3049 case Store: op = STORE_FAST; break;
3050 case Del: op = DELETE_FAST; break;
3051 case AugLoad:
3052 case AugStore:
3053 break;
3054 case Param:
3055 default:
3056 PyErr_SetString(PyExc_SystemError,
3057 "param invalid for local variable");
3058 return 0;
3059 }
3060 ADDOP_O(c, op, mangled, varnames);
3061 Py_DECREF(mangled);
3062 return 1;
3063 case OP_GLOBAL:
3064 switch (ctx) {
3065 case Load: op = LOAD_GLOBAL; break;
3066 case Store: op = STORE_GLOBAL; break;
3067 case Del: op = DELETE_GLOBAL; break;
3068 case AugLoad:
3069 case AugStore:
3070 break;
3071 case Param:
3072 default:
3073 PyErr_SetString(PyExc_SystemError,
3074 "param invalid for global variable");
3075 return 0;
3076 }
3077 break;
3078 case OP_NAME:
3079 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003080 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 case Store: op = STORE_NAME; break;
3082 case Del: op = DELETE_NAME; break;
3083 case AugLoad:
3084 case AugStore:
3085 break;
3086 case Param:
3087 default:
3088 PyErr_SetString(PyExc_SystemError,
3089 "param invalid for name variable");
3090 return 0;
3091 }
3092 break;
3093 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 assert(op);
3096 arg = compiler_add_o(c, dict, mangled);
3097 Py_DECREF(mangled);
3098 if (arg < 0)
3099 return 0;
3100 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101}
3102
3103static int
3104compiler_boolop(struct compiler *c, expr_ty e)
3105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003107 int jumpi;
3108 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 assert(e->kind == BoolOp_kind);
3112 if (e->v.BoolOp.op == And)
3113 jumpi = JUMP_IF_FALSE_OR_POP;
3114 else
3115 jumpi = JUMP_IF_TRUE_OR_POP;
3116 end = compiler_new_block(c);
3117 if (end == NULL)
3118 return 0;
3119 s = e->v.BoolOp.values;
3120 n = asdl_seq_LEN(s) - 1;
3121 assert(n >= 0);
3122 for (i = 0; i < n; ++i) {
3123 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3124 ADDOP_JABS(c, jumpi, end);
3125 }
3126 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3127 compiler_use_next_block(c, end);
3128 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003129}
3130
3131static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003132starunpack_helper(struct compiler *c, asdl_seq *elts,
3133 int single_op, int inner_op, int outer_op)
3134{
3135 Py_ssize_t n = asdl_seq_LEN(elts);
3136 Py_ssize_t i, nsubitems = 0, nseen = 0;
3137 for (i = 0; i < n; i++) {
3138 expr_ty elt = asdl_seq_GET(elts, i);
3139 if (elt->kind == Starred_kind) {
3140 if (nseen) {
3141 ADDOP_I(c, inner_op, nseen);
3142 nseen = 0;
3143 nsubitems++;
3144 }
3145 VISIT(c, expr, elt->v.Starred.value);
3146 nsubitems++;
3147 }
3148 else {
3149 VISIT(c, expr, elt);
3150 nseen++;
3151 }
3152 }
3153 if (nsubitems) {
3154 if (nseen) {
3155 ADDOP_I(c, inner_op, nseen);
3156 nsubitems++;
3157 }
3158 ADDOP_I(c, outer_op, nsubitems);
3159 }
3160 else
3161 ADDOP_I(c, single_op, nseen);
3162 return 1;
3163}
3164
3165static int
3166assignment_helper(struct compiler *c, asdl_seq *elts)
3167{
3168 Py_ssize_t n = asdl_seq_LEN(elts);
3169 Py_ssize_t i;
3170 int seen_star = 0;
3171 for (i = 0; i < n; i++) {
3172 expr_ty elt = asdl_seq_GET(elts, i);
3173 if (elt->kind == Starred_kind && !seen_star) {
3174 if ((i >= (1 << 8)) ||
3175 (n-i-1 >= (INT_MAX >> 8)))
3176 return compiler_error(c,
3177 "too many expressions in "
3178 "star-unpacking assignment");
3179 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3180 seen_star = 1;
3181 asdl_seq_SET(elts, i, elt->v.Starred.value);
3182 }
3183 else if (elt->kind == Starred_kind) {
3184 return compiler_error(c,
3185 "two starred expressions in assignment");
3186 }
3187 }
3188 if (!seen_star) {
3189 ADDOP_I(c, UNPACK_SEQUENCE, n);
3190 }
3191 VISIT_SEQ(c, expr, elts);
3192 return 1;
3193}
3194
3195static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196compiler_list(struct compiler *c, expr_ty e)
3197{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003198 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003200 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003202 else if (e->v.List.ctx == Load) {
3203 return starunpack_helper(c, elts,
3204 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003206 else
3207 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209}
3210
3211static int
3212compiler_tuple(struct compiler *c, expr_ty e)
3213{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003214 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003216 return assignment_helper(c, elts);
3217 }
3218 else if (e->v.Tuple.ctx == Load) {
3219 return starunpack_helper(c, elts,
3220 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3221 }
3222 else
3223 VISIT_SEQ(c, expr, elts);
3224 return 1;
3225}
3226
3227static int
3228compiler_set(struct compiler *c, expr_ty e)
3229{
3230 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3231 BUILD_SET, BUILD_SET_UNPACK);
3232}
3233
3234static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003235are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3236{
3237 Py_ssize_t i;
3238 for (i = begin; i < end; i++) {
3239 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3240 if (key == NULL || !is_const(key))
3241 return 0;
3242 }
3243 return 1;
3244}
3245
3246static int
3247compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3248{
3249 Py_ssize_t i, n = end - begin;
3250 PyObject *keys, *key;
3251 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3252 for (i = begin; i < end; i++) {
3253 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3254 }
3255 keys = PyTuple_New(n);
3256 if (keys == NULL) {
3257 return 0;
3258 }
3259 for (i = begin; i < end; i++) {
3260 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3261 Py_INCREF(key);
3262 PyTuple_SET_ITEM(keys, i - begin, key);
3263 }
3264 ADDOP_N(c, LOAD_CONST, keys, consts);
3265 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3266 }
3267 else {
3268 for (i = begin; i < end; i++) {
3269 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3270 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3271 }
3272 ADDOP_I(c, BUILD_MAP, n);
3273 }
3274 return 1;
3275}
3276
3277static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003278compiler_dict(struct compiler *c, expr_ty e)
3279{
Victor Stinner976bb402016-03-23 11:36:19 +01003280 Py_ssize_t i, n, elements;
3281 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003282 int is_unpacking = 0;
3283 n = asdl_seq_LEN(e->v.Dict.values);
3284 containers = 0;
3285 elements = 0;
3286 for (i = 0; i < n; i++) {
3287 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3288 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003289 if (!compiler_subdict(c, e, i - elements, i))
3290 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003291 containers++;
3292 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003294 if (is_unpacking) {
3295 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3296 containers++;
3297 }
3298 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003299 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 }
3301 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003302 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003303 if (!compiler_subdict(c, e, n - elements, n))
3304 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003305 containers++;
3306 }
3307 /* If there is more than one dict, they need to be merged into a new
3308 * dict. If there is one dict and it's an unpacking, then it needs
3309 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003310 if (containers > 1 || is_unpacking) {
3311 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 }
3313 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314}
3315
3316static int
3317compiler_compare(struct compiler *c, expr_ty e)
3318{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003319 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3323 VISIT(c, expr, e->v.Compare.left);
3324 n = asdl_seq_LEN(e->v.Compare.ops);
3325 assert(n > 0);
3326 if (n > 1) {
3327 cleanup = compiler_new_block(c);
3328 if (cleanup == NULL)
3329 return 0;
3330 VISIT(c, expr,
3331 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3332 }
3333 for (i = 1; i < n; i++) {
3334 ADDOP(c, DUP_TOP);
3335 ADDOP(c, ROT_THREE);
3336 ADDOP_I(c, COMPARE_OP,
3337 cmpop((cmpop_ty)(asdl_seq_GET(
3338 e->v.Compare.ops, i - 1))));
3339 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3340 NEXT_BLOCK(c);
3341 if (i < (n - 1))
3342 VISIT(c, expr,
3343 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3344 }
3345 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3346 ADDOP_I(c, COMPARE_OP,
3347 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3348 if (n > 1) {
3349 basicblock *end = compiler_new_block(c);
3350 if (end == NULL)
3351 return 0;
3352 ADDOP_JREL(c, JUMP_FORWARD, end);
3353 compiler_use_next_block(c, cleanup);
3354 ADDOP(c, ROT_TWO);
3355 ADDOP(c, POP_TOP);
3356 compiler_use_next_block(c, end);
3357 }
3358 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359}
3360
3361static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003362maybe_optimize_method_call(struct compiler *c, expr_ty e)
3363{
3364 Py_ssize_t argsl, i;
3365 expr_ty meth = e->v.Call.func;
3366 asdl_seq *args = e->v.Call.args;
3367
3368 /* Check that the call node is an attribute access, and that
3369 the call doesn't have keyword parameters. */
3370 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3371 asdl_seq_LEN(e->v.Call.keywords))
3372 return -1;
3373
3374 /* Check that there are no *varargs types of arguments. */
3375 argsl = asdl_seq_LEN(args);
3376 for (i = 0; i < argsl; i++) {
3377 expr_ty elt = asdl_seq_GET(args, i);
3378 if (elt->kind == Starred_kind) {
3379 return -1;
3380 }
3381 }
3382
3383 /* Alright, we can optimize the code. */
3384 VISIT(c, expr, meth->v.Attribute.value);
3385 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3386 VISIT_SEQ(c, expr, e->v.Call.args);
3387 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3388 return 1;
3389}
3390
3391static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392compiler_call(struct compiler *c, expr_ty e)
3393{
Yury Selivanovf2392132016-12-13 19:03:51 -05003394 if (maybe_optimize_method_call(c, e) > 0)
3395 return 1;
3396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 VISIT(c, expr, e->v.Call.func);
3398 return compiler_call_helper(c, 0,
3399 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003400 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003401}
3402
Eric V. Smith235a6f02015-09-19 14:51:32 -04003403static int
3404compiler_joined_str(struct compiler *c, expr_ty e)
3405{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003406 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003407 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3408 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003409 return 1;
3410}
3411
Eric V. Smitha78c7952015-11-03 12:45:05 -05003412/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003413static int
3414compiler_formatted_value(struct compiler *c, expr_ty e)
3415{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003416 /* Our oparg encodes 2 pieces of information: the conversion
3417 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003418
Eric V. Smitha78c7952015-11-03 12:45:05 -05003419 Convert the conversion char to 2 bits:
3420 None: 000 0x0 FVC_NONE
3421 !s : 001 0x1 FVC_STR
3422 !r : 010 0x2 FVC_REPR
3423 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003424
Eric V. Smitha78c7952015-11-03 12:45:05 -05003425 next bit is whether or not we have a format spec:
3426 yes : 100 0x4
3427 no : 000 0x0
3428 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003429
Eric V. Smitha78c7952015-11-03 12:45:05 -05003430 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003431
Eric V. Smitha78c7952015-11-03 12:45:05 -05003432 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003433 VISIT(c, expr, e->v.FormattedValue.value);
3434
Eric V. Smitha78c7952015-11-03 12:45:05 -05003435 switch (e->v.FormattedValue.conversion) {
3436 case 's': oparg = FVC_STR; break;
3437 case 'r': oparg = FVC_REPR; break;
3438 case 'a': oparg = FVC_ASCII; break;
3439 case -1: oparg = FVC_NONE; break;
3440 default:
3441 PyErr_SetString(PyExc_SystemError,
3442 "Unrecognized conversion character");
3443 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003444 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003445 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003446 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003447 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003448 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003449 }
3450
Eric V. Smitha78c7952015-11-03 12:45:05 -05003451 /* And push our opcode and oparg */
3452 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003453 return 1;
3454}
3455
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003456static int
3457compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3458{
3459 Py_ssize_t i, n = end - begin;
3460 keyword_ty kw;
3461 PyObject *keys, *key;
3462 assert(n > 0);
3463 if (n > 1) {
3464 for (i = begin; i < end; i++) {
3465 kw = asdl_seq_GET(keywords, i);
3466 VISIT(c, expr, kw->value);
3467 }
3468 keys = PyTuple_New(n);
3469 if (keys == NULL) {
3470 return 0;
3471 }
3472 for (i = begin; i < end; i++) {
3473 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3474 Py_INCREF(key);
3475 PyTuple_SET_ITEM(keys, i - begin, key);
3476 }
3477 ADDOP_N(c, LOAD_CONST, keys, consts);
3478 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3479 }
3480 else {
3481 /* a for loop only executes once */
3482 for (i = begin; i < end; i++) {
3483 kw = asdl_seq_GET(keywords, i);
3484 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3485 VISIT(c, expr, kw->value);
3486 }
3487 ADDOP_I(c, BUILD_MAP, n);
3488 }
3489 return 1;
3490}
3491
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003492/* shared code between compiler_call and compiler_class */
3493static int
3494compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003495 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003496 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003497 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003498{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003499 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003500 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003501
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003502 /* the number of tuples and dictionaries on the stack */
3503 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3504
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003505 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003506 nkwelts = asdl_seq_LEN(keywords);
3507
3508 for (i = 0; i < nkwelts; i++) {
3509 keyword_ty kw = asdl_seq_GET(keywords, i);
3510 if (kw->arg == NULL) {
3511 mustdictunpack = 1;
3512 break;
3513 }
3514 }
3515
3516 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003517 for (i = 0; i < nelts; i++) {
3518 expr_ty elt = asdl_seq_GET(args, i);
3519 if (elt->kind == Starred_kind) {
3520 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003521 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003522 if (nseen) {
3523 ADDOP_I(c, BUILD_TUPLE, nseen);
3524 nseen = 0;
3525 nsubargs++;
3526 }
3527 VISIT(c, expr, elt->v.Starred.value);
3528 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003529 }
3530 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003531 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003532 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003533 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003535
3536 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003537 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003538 if (nseen) {
3539 /* Pack up any trailing positional arguments. */
3540 ADDOP_I(c, BUILD_TUPLE, nseen);
3541 nsubargs++;
3542 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003543 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003544 /* If we ended up with more than one stararg, we need
3545 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003546 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003547 }
3548 else if (nsubargs == 0) {
3549 ADDOP_I(c, BUILD_TUPLE, 0);
3550 }
3551 nseen = 0; /* the number of keyword arguments on the stack following */
3552 for (i = 0; i < nkwelts; i++) {
3553 keyword_ty kw = asdl_seq_GET(keywords, i);
3554 if (kw->arg == NULL) {
3555 /* A keyword argument unpacking. */
3556 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003557 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3558 return 0;
3559 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003560 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003561 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003562 VISIT(c, expr, kw->value);
3563 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003564 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003565 else {
3566 nseen++;
3567 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003568 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003569 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003570 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003571 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003572 return 0;
3573 nsubkwargs++;
3574 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003575 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003576 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003577 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003578 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003579 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3580 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003582 else if (nkwelts) {
3583 PyObject *names;
3584 VISIT_SEQ(c, keyword, keywords);
3585 names = PyTuple_New(nkwelts);
3586 if (names == NULL) {
3587 return 0;
3588 }
3589 for (i = 0; i < nkwelts; i++) {
3590 keyword_ty kw = asdl_seq_GET(keywords, i);
3591 Py_INCREF(kw->arg);
3592 PyTuple_SET_ITEM(names, i, kw->arg);
3593 }
3594 ADDOP_N(c, LOAD_CONST, names, consts);
3595 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3596 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003598 else {
3599 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3600 return 1;
3601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602}
3603
Nick Coghlan650f0d02007-04-15 12:05:43 +00003604
3605/* List and set comprehensions and generator expressions work by creating a
3606 nested function to perform the actual iteration. This means that the
3607 iteration variables don't leak into the current scope.
3608 The defined function is called immediately following its definition, with the
3609 result of that call being the result of the expression.
3610 The LC/SC version returns the populated container, while the GE version is
3611 flagged in symtable.c as a generator, so it returns the generator object
3612 when the function is called.
3613 This code *knows* that the loop cannot contain break, continue, or return,
3614 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3615
3616 Possible cleanups:
3617 - iterate over the generator sequence instead of using recursion
3618*/
3619
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003620
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622compiler_comprehension_generator(struct compiler *c,
3623 asdl_seq *generators, int gen_index,
3624 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003626 comprehension_ty gen;
3627 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3628 if (gen->is_async) {
3629 return compiler_async_comprehension_generator(
3630 c, generators, gen_index, elt, val, type);
3631 } else {
3632 return compiler_sync_comprehension_generator(
3633 c, generators, gen_index, elt, val, type);
3634 }
3635}
3636
3637static int
3638compiler_sync_comprehension_generator(struct compiler *c,
3639 asdl_seq *generators, int gen_index,
3640 expr_ty elt, expr_ty val, int type)
3641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 /* generate code for the iterator, then each of the ifs,
3643 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 comprehension_ty gen;
3646 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003647 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 start = compiler_new_block(c);
3650 skip = compiler_new_block(c);
3651 if_cleanup = compiler_new_block(c);
3652 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3655 anchor == NULL)
3656 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (gen_index == 0) {
3661 /* Receive outermost iter as an implicit argument */
3662 c->u->u_argcount = 1;
3663 ADDOP_I(c, LOAD_FAST, 0);
3664 }
3665 else {
3666 /* Sub-iter - calculate on the fly */
3667 VISIT(c, expr, gen->iter);
3668 ADDOP(c, GET_ITER);
3669 }
3670 compiler_use_next_block(c, start);
3671 ADDOP_JREL(c, FOR_ITER, anchor);
3672 NEXT_BLOCK(c);
3673 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 /* XXX this needs to be cleaned up...a lot! */
3676 n = asdl_seq_LEN(gen->ifs);
3677 for (i = 0; i < n; i++) {
3678 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3679 VISIT(c, expr, e);
3680 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3681 NEXT_BLOCK(c);
3682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 if (++gen_index < asdl_seq_LEN(generators))
3685 if (!compiler_comprehension_generator(c,
3686 generators, gen_index,
3687 elt, val, type))
3688 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 /* only append after the last for generator */
3691 if (gen_index >= asdl_seq_LEN(generators)) {
3692 /* comprehension specific code */
3693 switch (type) {
3694 case COMP_GENEXP:
3695 VISIT(c, expr, elt);
3696 ADDOP(c, YIELD_VALUE);
3697 ADDOP(c, POP_TOP);
3698 break;
3699 case COMP_LISTCOMP:
3700 VISIT(c, expr, elt);
3701 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3702 break;
3703 case COMP_SETCOMP:
3704 VISIT(c, expr, elt);
3705 ADDOP_I(c, SET_ADD, gen_index + 1);
3706 break;
3707 case COMP_DICTCOMP:
3708 /* With 'd[k] = v', v is evaluated before k, so we do
3709 the same. */
3710 VISIT(c, expr, val);
3711 VISIT(c, expr, elt);
3712 ADDOP_I(c, MAP_ADD, gen_index + 1);
3713 break;
3714 default:
3715 return 0;
3716 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 compiler_use_next_block(c, skip);
3719 }
3720 compiler_use_next_block(c, if_cleanup);
3721 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3722 compiler_use_next_block(c, anchor);
3723
3724 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725}
3726
3727static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003728compiler_async_comprehension_generator(struct compiler *c,
3729 asdl_seq *generators, int gen_index,
3730 expr_ty elt, expr_ty val, int type)
3731{
3732 _Py_IDENTIFIER(StopAsyncIteration);
3733
3734 comprehension_ty gen;
3735 basicblock *anchor, *skip, *if_cleanup, *try,
3736 *after_try, *except, *try_cleanup;
3737 Py_ssize_t i, n;
3738
3739 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3740 if (stop_aiter_error == NULL) {
3741 return 0;
3742 }
3743
3744 try = compiler_new_block(c);
3745 after_try = compiler_new_block(c);
3746 try_cleanup = compiler_new_block(c);
3747 except = compiler_new_block(c);
3748 skip = compiler_new_block(c);
3749 if_cleanup = compiler_new_block(c);
3750 anchor = compiler_new_block(c);
3751
3752 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3753 try == NULL || after_try == NULL ||
3754 except == NULL || after_try == NULL) {
3755 return 0;
3756 }
3757
3758 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3759
3760 if (gen_index == 0) {
3761 /* Receive outermost iter as an implicit argument */
3762 c->u->u_argcount = 1;
3763 ADDOP_I(c, LOAD_FAST, 0);
3764 }
3765 else {
3766 /* Sub-iter - calculate on the fly */
3767 VISIT(c, expr, gen->iter);
3768 ADDOP(c, GET_AITER);
3769 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3770 ADDOP(c, YIELD_FROM);
3771 }
3772
3773 compiler_use_next_block(c, try);
3774
3775
3776 ADDOP_JREL(c, SETUP_EXCEPT, except);
3777 if (!compiler_push_fblock(c, EXCEPT, try))
3778 return 0;
3779
3780 ADDOP(c, GET_ANEXT);
3781 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3782 ADDOP(c, YIELD_FROM);
3783 VISIT(c, expr, gen->target);
3784 ADDOP(c, POP_BLOCK);
3785 compiler_pop_fblock(c, EXCEPT, try);
3786 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3787
3788
3789 compiler_use_next_block(c, except);
3790 ADDOP(c, DUP_TOP);
3791 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3792 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3793 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3794
3795 ADDOP(c, POP_TOP);
3796 ADDOP(c, POP_TOP);
3797 ADDOP(c, POP_TOP);
3798 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3799 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3800
3801
3802 compiler_use_next_block(c, try_cleanup);
3803 ADDOP(c, END_FINALLY);
3804
3805 compiler_use_next_block(c, after_try);
3806
3807 n = asdl_seq_LEN(gen->ifs);
3808 for (i = 0; i < n; i++) {
3809 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3810 VISIT(c, expr, e);
3811 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3812 NEXT_BLOCK(c);
3813 }
3814
3815 if (++gen_index < asdl_seq_LEN(generators))
3816 if (!compiler_comprehension_generator(c,
3817 generators, gen_index,
3818 elt, val, type))
3819 return 0;
3820
3821 /* only append after the last for generator */
3822 if (gen_index >= asdl_seq_LEN(generators)) {
3823 /* comprehension specific code */
3824 switch (type) {
3825 case COMP_GENEXP:
3826 VISIT(c, expr, elt);
3827 ADDOP(c, YIELD_VALUE);
3828 ADDOP(c, POP_TOP);
3829 break;
3830 case COMP_LISTCOMP:
3831 VISIT(c, expr, elt);
3832 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3833 break;
3834 case COMP_SETCOMP:
3835 VISIT(c, expr, elt);
3836 ADDOP_I(c, SET_ADD, gen_index + 1);
3837 break;
3838 case COMP_DICTCOMP:
3839 /* With 'd[k] = v', v is evaluated before k, so we do
3840 the same. */
3841 VISIT(c, expr, val);
3842 VISIT(c, expr, elt);
3843 ADDOP_I(c, MAP_ADD, gen_index + 1);
3844 break;
3845 default:
3846 return 0;
3847 }
3848
3849 compiler_use_next_block(c, skip);
3850 }
3851 compiler_use_next_block(c, if_cleanup);
3852 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3853 compiler_use_next_block(c, anchor);
3854 ADDOP(c, POP_TOP);
3855
3856 return 1;
3857}
3858
3859static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003860compiler_comprehension(struct compiler *c, expr_ty e, int type,
3861 identifier name, asdl_seq *generators, expr_ty elt,
3862 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003865 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003866 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003867 int is_async_function = c->u->u_ste->ste_coroutine;
3868 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003869
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003870 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003871
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003872 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3873 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003874 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003876 }
3877
3878 is_async_generator = c->u->u_ste->ste_coroutine;
3879
3880 if (is_async_generator && !is_async_function) {
3881 if (e->lineno > c->u->u_lineno) {
3882 c->u->u_lineno = e->lineno;
3883 c->u->u_lineno_set = 0;
3884 }
3885 compiler_error(c, "asynchronous comprehension outside of "
3886 "an asynchronous function");
3887 goto error_in_scope;
3888 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 if (type != COMP_GENEXP) {
3891 int op;
3892 switch (type) {
3893 case COMP_LISTCOMP:
3894 op = BUILD_LIST;
3895 break;
3896 case COMP_SETCOMP:
3897 op = BUILD_SET;
3898 break;
3899 case COMP_DICTCOMP:
3900 op = BUILD_MAP;
3901 break;
3902 default:
3903 PyErr_Format(PyExc_SystemError,
3904 "unknown comprehension type %d", type);
3905 goto error_in_scope;
3906 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 ADDOP_I(c, op, 0);
3909 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 if (!compiler_comprehension_generator(c, generators, 0, elt,
3912 val, type))
3913 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 if (type != COMP_GENEXP) {
3916 ADDOP(c, RETURN_VALUE);
3917 }
3918
3919 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003920 qualname = c->u->u_qualname;
3921 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003923 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 goto error;
3925
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003926 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003928 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 Py_DECREF(co);
3930
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003931 VISIT(c, expr, outermost->iter);
3932
3933 if (outermost->is_async) {
3934 ADDOP(c, GET_AITER);
3935 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3936 ADDOP(c, YIELD_FROM);
3937 } else {
3938 ADDOP(c, GET_ITER);
3939 }
3940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003942
3943 if (is_async_generator && type != COMP_GENEXP) {
3944 ADDOP(c, GET_AWAITABLE);
3945 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3946 ADDOP(c, YIELD_FROM);
3947 }
3948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003950error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003952error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003953 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 Py_XDECREF(co);
3955 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003956}
3957
3958static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003959compiler_genexp(struct compiler *c, expr_ty e)
3960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 static identifier name;
3962 if (!name) {
3963 name = PyUnicode_FromString("<genexpr>");
3964 if (!name)
3965 return 0;
3966 }
3967 assert(e->kind == GeneratorExp_kind);
3968 return compiler_comprehension(c, e, COMP_GENEXP, name,
3969 e->v.GeneratorExp.generators,
3970 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003971}
3972
3973static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003974compiler_listcomp(struct compiler *c, expr_ty e)
3975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 static identifier name;
3977 if (!name) {
3978 name = PyUnicode_FromString("<listcomp>");
3979 if (!name)
3980 return 0;
3981 }
3982 assert(e->kind == ListComp_kind);
3983 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3984 e->v.ListComp.generators,
3985 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003986}
3987
3988static int
3989compiler_setcomp(struct compiler *c, expr_ty e)
3990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 static identifier name;
3992 if (!name) {
3993 name = PyUnicode_FromString("<setcomp>");
3994 if (!name)
3995 return 0;
3996 }
3997 assert(e->kind == SetComp_kind);
3998 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3999 e->v.SetComp.generators,
4000 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004001}
4002
4003
4004static int
4005compiler_dictcomp(struct compiler *c, expr_ty e)
4006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 static identifier name;
4008 if (!name) {
4009 name = PyUnicode_FromString("<dictcomp>");
4010 if (!name)
4011 return 0;
4012 }
4013 assert(e->kind == DictComp_kind);
4014 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4015 e->v.DictComp.generators,
4016 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004017}
4018
4019
4020static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021compiler_visit_keyword(struct compiler *c, keyword_ty k)
4022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 VISIT(c, expr, k->value);
4024 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025}
4026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 whether they are true or false.
4029
4030 Return values: 1 for true, 0 for false, -1 for non-constant.
4031 */
4032
4033static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004034expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004035{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004036 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 switch (e->kind) {
4038 case Ellipsis_kind:
4039 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004040 case Constant_kind:
4041 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 case Num_kind:
4043 return PyObject_IsTrue(e->v.Num.n);
4044 case Str_kind:
4045 return PyObject_IsTrue(e->v.Str.s);
4046 case Name_kind:
4047 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004048 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004049 if (id && strcmp(id, "__debug__") == 0)
4050 return !c->c_optimize;
4051 return -1;
4052 case NameConstant_kind: {
4053 PyObject *o = e->v.NameConstant.value;
4054 if (o == Py_None)
4055 return 0;
4056 else if (o == Py_True)
4057 return 1;
4058 else if (o == Py_False)
4059 return 0;
4060 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 default:
4062 return -1;
4063 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064}
4065
Yury Selivanov75445082015-05-11 22:57:16 -04004066
4067/*
4068 Implements the async with statement.
4069
4070 The semantics outlined in that PEP are as follows:
4071
4072 async with EXPR as VAR:
4073 BLOCK
4074
4075 It is implemented roughly as:
4076
4077 context = EXPR
4078 exit = context.__aexit__ # not calling it
4079 value = await context.__aenter__()
4080 try:
4081 VAR = value # if VAR present in the syntax
4082 BLOCK
4083 finally:
4084 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004085 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004086 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004087 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004088 if not (await exit(*exc)):
4089 raise
4090 */
4091static int
4092compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4093{
4094 basicblock *block, *finally;
4095 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4096
4097 assert(s->kind == AsyncWith_kind);
4098
4099 block = compiler_new_block(c);
4100 finally = compiler_new_block(c);
4101 if (!block || !finally)
4102 return 0;
4103
4104 /* Evaluate EXPR */
4105 VISIT(c, expr, item->context_expr);
4106
4107 ADDOP(c, BEFORE_ASYNC_WITH);
4108 ADDOP(c, GET_AWAITABLE);
4109 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4110 ADDOP(c, YIELD_FROM);
4111
4112 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4113
4114 /* SETUP_ASYNC_WITH pushes a finally block. */
4115 compiler_use_next_block(c, block);
4116 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4117 return 0;
4118 }
4119
4120 if (item->optional_vars) {
4121 VISIT(c, expr, item->optional_vars);
4122 }
4123 else {
4124 /* Discard result from context.__aenter__() */
4125 ADDOP(c, POP_TOP);
4126 }
4127
4128 pos++;
4129 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4130 /* BLOCK code */
4131 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4132 else if (!compiler_async_with(c, s, pos))
4133 return 0;
4134
4135 /* End of try block; start the finally block */
4136 ADDOP(c, POP_BLOCK);
4137 compiler_pop_fblock(c, FINALLY_TRY, block);
4138
4139 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4140 compiler_use_next_block(c, finally);
4141 if (!compiler_push_fblock(c, FINALLY_END, finally))
4142 return 0;
4143
4144 /* Finally block starts; context.__exit__ is on the stack under
4145 the exception or return information. Just issue our magic
4146 opcode. */
4147 ADDOP(c, WITH_CLEANUP_START);
4148
4149 ADDOP(c, GET_AWAITABLE);
4150 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4151 ADDOP(c, YIELD_FROM);
4152
4153 ADDOP(c, WITH_CLEANUP_FINISH);
4154
4155 /* Finally block ends. */
4156 ADDOP(c, END_FINALLY);
4157 compiler_pop_fblock(c, FINALLY_END, finally);
4158 return 1;
4159}
4160
4161
Guido van Rossumc2e20742006-02-27 22:32:47 +00004162/*
4163 Implements the with statement from PEP 343.
4164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004166
4167 with EXPR as VAR:
4168 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169
Guido van Rossumc2e20742006-02-27 22:32:47 +00004170 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171
Thomas Wouters477c8d52006-05-27 19:21:47 +00004172 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004173 exit = context.__exit__ # not calling it
4174 value = context.__enter__()
4175 try:
4176 VAR = value # if VAR present in the syntax
4177 BLOCK
4178 finally:
4179 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004180 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004181 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004182 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004183 exit(*exc)
4184 */
4185static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004186compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004187{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004188 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004189 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004190
4191 assert(s->kind == With_kind);
4192
Guido van Rossumc2e20742006-02-27 22:32:47 +00004193 block = compiler_new_block(c);
4194 finally = compiler_new_block(c);
4195 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004196 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004197
Thomas Wouters477c8d52006-05-27 19:21:47 +00004198 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004199 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004200 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004201
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004202 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004203 compiler_use_next_block(c, block);
4204 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004205 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004206 }
4207
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004208 if (item->optional_vars) {
4209 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004210 }
4211 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004213 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004214 }
4215
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004216 pos++;
4217 if (pos == asdl_seq_LEN(s->v.With.items))
4218 /* BLOCK code */
4219 VISIT_SEQ(c, stmt, s->v.With.body)
4220 else if (!compiler_with(c, s, pos))
4221 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004222
4223 /* End of try block; start the finally block */
4224 ADDOP(c, POP_BLOCK);
4225 compiler_pop_fblock(c, FINALLY_TRY, block);
4226
4227 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4228 compiler_use_next_block(c, finally);
4229 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004230 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004231
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004232 /* Finally block starts; context.__exit__ is on the stack under
4233 the exception or return information. Just issue our magic
4234 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004235 ADDOP(c, WITH_CLEANUP_START);
4236 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004237
4238 /* Finally block ends. */
4239 ADDOP(c, END_FINALLY);
4240 compiler_pop_fblock(c, FINALLY_END, finally);
4241 return 1;
4242}
4243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004244static int
4245compiler_visit_expr(struct compiler *c, expr_ty e)
4246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 /* If expr e has a different line number than the last expr/stmt,
4248 set a new line number for the next instruction.
4249 */
4250 if (e->lineno > c->u->u_lineno) {
4251 c->u->u_lineno = e->lineno;
4252 c->u->u_lineno_set = 0;
4253 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004254 /* Updating the column offset is always harmless. */
4255 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 switch (e->kind) {
4257 case BoolOp_kind:
4258 return compiler_boolop(c, e);
4259 case BinOp_kind:
4260 VISIT(c, expr, e->v.BinOp.left);
4261 VISIT(c, expr, e->v.BinOp.right);
4262 ADDOP(c, binop(c, e->v.BinOp.op));
4263 break;
4264 case UnaryOp_kind:
4265 VISIT(c, expr, e->v.UnaryOp.operand);
4266 ADDOP(c, unaryop(e->v.UnaryOp.op));
4267 break;
4268 case Lambda_kind:
4269 return compiler_lambda(c, e);
4270 case IfExp_kind:
4271 return compiler_ifexp(c, e);
4272 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004273 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004275 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 case GeneratorExp_kind:
4277 return compiler_genexp(c, e);
4278 case ListComp_kind:
4279 return compiler_listcomp(c, e);
4280 case SetComp_kind:
4281 return compiler_setcomp(c, e);
4282 case DictComp_kind:
4283 return compiler_dictcomp(c, e);
4284 case Yield_kind:
4285 if (c->u->u_ste->ste_type != FunctionBlock)
4286 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004287 if (e->v.Yield.value) {
4288 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 }
4290 else {
4291 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4292 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004293 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004295 case YieldFrom_kind:
4296 if (c->u->u_ste->ste_type != FunctionBlock)
4297 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004298
4299 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4300 return compiler_error(c, "'yield from' inside async function");
4301
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004302 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004303 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004304 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4305 ADDOP(c, YIELD_FROM);
4306 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004307 case Await_kind:
4308 if (c->u->u_ste->ste_type != FunctionBlock)
4309 return compiler_error(c, "'await' outside function");
4310
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004311 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4312 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004313 return compiler_error(c, "'await' outside async function");
4314
4315 VISIT(c, expr, e->v.Await.value);
4316 ADDOP(c, GET_AWAITABLE);
4317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4318 ADDOP(c, YIELD_FROM);
4319 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 case Compare_kind:
4321 return compiler_compare(c, e);
4322 case Call_kind:
4323 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004324 case Constant_kind:
4325 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4326 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 case Num_kind:
4328 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4329 break;
4330 case Str_kind:
4331 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4332 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004333 case JoinedStr_kind:
4334 return compiler_joined_str(c, e);
4335 case FormattedValue_kind:
4336 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 case Bytes_kind:
4338 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4339 break;
4340 case Ellipsis_kind:
4341 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4342 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004343 case NameConstant_kind:
4344 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4345 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 /* The following exprs can be assignment targets. */
4347 case Attribute_kind:
4348 if (e->v.Attribute.ctx != AugStore)
4349 VISIT(c, expr, e->v.Attribute.value);
4350 switch (e->v.Attribute.ctx) {
4351 case AugLoad:
4352 ADDOP(c, DUP_TOP);
4353 /* Fall through to load */
4354 case Load:
4355 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4356 break;
4357 case AugStore:
4358 ADDOP(c, ROT_TWO);
4359 /* Fall through to save */
4360 case Store:
4361 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4362 break;
4363 case Del:
4364 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4365 break;
4366 case Param:
4367 default:
4368 PyErr_SetString(PyExc_SystemError,
4369 "param invalid in attribute expression");
4370 return 0;
4371 }
4372 break;
4373 case Subscript_kind:
4374 switch (e->v.Subscript.ctx) {
4375 case AugLoad:
4376 VISIT(c, expr, e->v.Subscript.value);
4377 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4378 break;
4379 case Load:
4380 VISIT(c, expr, e->v.Subscript.value);
4381 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4382 break;
4383 case AugStore:
4384 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4385 break;
4386 case Store:
4387 VISIT(c, expr, e->v.Subscript.value);
4388 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4389 break;
4390 case Del:
4391 VISIT(c, expr, e->v.Subscript.value);
4392 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4393 break;
4394 case Param:
4395 default:
4396 PyErr_SetString(PyExc_SystemError,
4397 "param invalid in subscript expression");
4398 return 0;
4399 }
4400 break;
4401 case Starred_kind:
4402 switch (e->v.Starred.ctx) {
4403 case Store:
4404 /* In all legitimate cases, the Starred node was already replaced
4405 * by compiler_list/compiler_tuple. XXX: is that okay? */
4406 return compiler_error(c,
4407 "starred assignment target must be in a list or tuple");
4408 default:
4409 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004410 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 }
4412 break;
4413 case Name_kind:
4414 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4415 /* child nodes of List and Tuple will have expr_context set */
4416 case List_kind:
4417 return compiler_list(c, e);
4418 case Tuple_kind:
4419 return compiler_tuple(c, e);
4420 }
4421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422}
4423
4424static int
4425compiler_augassign(struct compiler *c, stmt_ty s)
4426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 expr_ty e = s->v.AugAssign.target;
4428 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 switch (e->kind) {
4433 case Attribute_kind:
4434 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4435 AugLoad, e->lineno, e->col_offset, c->c_arena);
4436 if (auge == NULL)
4437 return 0;
4438 VISIT(c, expr, auge);
4439 VISIT(c, expr, s->v.AugAssign.value);
4440 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4441 auge->v.Attribute.ctx = AugStore;
4442 VISIT(c, expr, auge);
4443 break;
4444 case Subscript_kind:
4445 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4446 AugLoad, e->lineno, e->col_offset, c->c_arena);
4447 if (auge == NULL)
4448 return 0;
4449 VISIT(c, expr, auge);
4450 VISIT(c, expr, s->v.AugAssign.value);
4451 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4452 auge->v.Subscript.ctx = AugStore;
4453 VISIT(c, expr, auge);
4454 break;
4455 case Name_kind:
4456 if (!compiler_nameop(c, e->v.Name.id, Load))
4457 return 0;
4458 VISIT(c, expr, s->v.AugAssign.value);
4459 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4460 return compiler_nameop(c, e->v.Name.id, Store);
4461 default:
4462 PyErr_Format(PyExc_SystemError,
4463 "invalid node type (%d) for augmented assignment",
4464 e->kind);
4465 return 0;
4466 }
4467 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004468}
4469
4470static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004471check_ann_expr(struct compiler *c, expr_ty e)
4472{
4473 VISIT(c, expr, e);
4474 ADDOP(c, POP_TOP);
4475 return 1;
4476}
4477
4478static int
4479check_annotation(struct compiler *c, stmt_ty s)
4480{
4481 /* Annotations are only evaluated in a module or class. */
4482 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4483 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4484 return check_ann_expr(c, s->v.AnnAssign.annotation);
4485 }
4486 return 1;
4487}
4488
4489static int
4490check_ann_slice(struct compiler *c, slice_ty sl)
4491{
4492 switch(sl->kind) {
4493 case Index_kind:
4494 return check_ann_expr(c, sl->v.Index.value);
4495 case Slice_kind:
4496 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4497 return 0;
4498 }
4499 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4500 return 0;
4501 }
4502 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4503 return 0;
4504 }
4505 break;
4506 default:
4507 PyErr_SetString(PyExc_SystemError,
4508 "unexpected slice kind");
4509 return 0;
4510 }
4511 return 1;
4512}
4513
4514static int
4515check_ann_subscr(struct compiler *c, slice_ty sl)
4516{
4517 /* We check that everything in a subscript is defined at runtime. */
4518 Py_ssize_t i, n;
4519
4520 switch (sl->kind) {
4521 case Index_kind:
4522 case Slice_kind:
4523 if (!check_ann_slice(c, sl)) {
4524 return 0;
4525 }
4526 break;
4527 case ExtSlice_kind:
4528 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4529 for (i = 0; i < n; i++) {
4530 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4531 switch (subsl->kind) {
4532 case Index_kind:
4533 case Slice_kind:
4534 if (!check_ann_slice(c, subsl)) {
4535 return 0;
4536 }
4537 break;
4538 case ExtSlice_kind:
4539 default:
4540 PyErr_SetString(PyExc_SystemError,
4541 "extended slice invalid in nested slice");
4542 return 0;
4543 }
4544 }
4545 break;
4546 default:
4547 PyErr_Format(PyExc_SystemError,
4548 "invalid subscript kind %d", sl->kind);
4549 return 0;
4550 }
4551 return 1;
4552}
4553
4554static int
4555compiler_annassign(struct compiler *c, stmt_ty s)
4556{
4557 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004558 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004559
4560 assert(s->kind == AnnAssign_kind);
4561
4562 /* We perform the actual assignment first. */
4563 if (s->v.AnnAssign.value) {
4564 VISIT(c, expr, s->v.AnnAssign.value);
4565 VISIT(c, expr, targ);
4566 }
4567 switch (targ->kind) {
4568 case Name_kind:
4569 /* If we have a simple name in a module or class, store annotation. */
4570 if (s->v.AnnAssign.simple &&
4571 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4572 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004573 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4574 if (!mangled) {
4575 return 0;
4576 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004577 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004578 /* ADDOP_N decrefs its argument */
4579 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004580 }
4581 break;
4582 case Attribute_kind:
4583 if (!s->v.AnnAssign.value &&
4584 !check_ann_expr(c, targ->v.Attribute.value)) {
4585 return 0;
4586 }
4587 break;
4588 case Subscript_kind:
4589 if (!s->v.AnnAssign.value &&
4590 (!check_ann_expr(c, targ->v.Subscript.value) ||
4591 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4592 return 0;
4593 }
4594 break;
4595 default:
4596 PyErr_Format(PyExc_SystemError,
4597 "invalid node type (%d) for annotated assignment",
4598 targ->kind);
4599 return 0;
4600 }
4601 /* Annotation is evaluated last. */
4602 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4603 return 0;
4604 }
4605 return 1;
4606}
4607
4608static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004609compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 struct fblockinfo *f;
4612 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004613 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 "too many statically nested blocks");
4615 return 0;
4616 }
4617 f = &c->u->u_fblock[c->u->u_nfblocks++];
4618 f->fb_type = t;
4619 f->fb_block = b;
4620 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004621}
4622
4623static void
4624compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 struct compiler_unit *u = c->u;
4627 assert(u->u_nfblocks > 0);
4628 u->u_nfblocks--;
4629 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4630 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004631}
4632
Thomas Wouters89f507f2006-12-13 04:49:30 +00004633static int
4634compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 int i;
4636 struct compiler_unit *u = c->u;
4637 for (i = 0; i < u->u_nfblocks; ++i) {
4638 if (u->u_fblock[i].fb_type == LOOP)
4639 return 1;
4640 }
4641 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004642}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004643/* Raises a SyntaxError and returns 0.
4644 If something goes wrong, a different exception may be raised.
4645*/
4646
4647static int
4648compiler_error(struct compiler *c, const char *errstr)
4649{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004650 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004652
Victor Stinner14e461d2013-08-26 22:28:21 +02004653 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 if (!loc) {
4655 Py_INCREF(Py_None);
4656 loc = Py_None;
4657 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004658 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004659 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 if (!u)
4661 goto exit;
4662 v = Py_BuildValue("(zO)", errstr, u);
4663 if (!v)
4664 goto exit;
4665 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004666 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 Py_DECREF(loc);
4668 Py_XDECREF(u);
4669 Py_XDECREF(v);
4670 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004671}
4672
4673static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674compiler_handle_subscr(struct compiler *c, const char *kind,
4675 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 /* XXX this code is duplicated */
4680 switch (ctx) {
4681 case AugLoad: /* fall through to Load */
4682 case Load: op = BINARY_SUBSCR; break;
4683 case AugStore:/* fall through to Store */
4684 case Store: op = STORE_SUBSCR; break;
4685 case Del: op = DELETE_SUBSCR; break;
4686 case Param:
4687 PyErr_Format(PyExc_SystemError,
4688 "invalid %s kind %d in subscript\n",
4689 kind, ctx);
4690 return 0;
4691 }
4692 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004693 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 }
4695 else if (ctx == AugStore) {
4696 ADDOP(c, ROT_THREE);
4697 }
4698 ADDOP(c, op);
4699 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004700}
4701
4702static int
4703compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 int n = 2;
4706 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 /* only handles the cases where BUILD_SLICE is emitted */
4709 if (s->v.Slice.lower) {
4710 VISIT(c, expr, s->v.Slice.lower);
4711 }
4712 else {
4713 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4714 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (s->v.Slice.upper) {
4717 VISIT(c, expr, s->v.Slice.upper);
4718 }
4719 else {
4720 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4721 }
4722
4723 if (s->v.Slice.step) {
4724 n++;
4725 VISIT(c, expr, s->v.Slice.step);
4726 }
4727 ADDOP_I(c, BUILD_SLICE, n);
4728 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004729}
4730
4731static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4733 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 switch (s->kind) {
4736 case Slice_kind:
4737 return compiler_slice(c, s, ctx);
4738 case Index_kind:
4739 VISIT(c, expr, s->v.Index.value);
4740 break;
4741 case ExtSlice_kind:
4742 default:
4743 PyErr_SetString(PyExc_SystemError,
4744 "extended slice invalid in nested slice");
4745 return 0;
4746 }
4747 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748}
4749
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004750static int
4751compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 char * kindname = NULL;
4754 switch (s->kind) {
4755 case Index_kind:
4756 kindname = "index";
4757 if (ctx != AugStore) {
4758 VISIT(c, expr, s->v.Index.value);
4759 }
4760 break;
4761 case Slice_kind:
4762 kindname = "slice";
4763 if (ctx != AugStore) {
4764 if (!compiler_slice(c, s, ctx))
4765 return 0;
4766 }
4767 break;
4768 case ExtSlice_kind:
4769 kindname = "extended slice";
4770 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004771 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 for (i = 0; i < n; i++) {
4773 slice_ty sub = (slice_ty)asdl_seq_GET(
4774 s->v.ExtSlice.dims, i);
4775 if (!compiler_visit_nested_slice(c, sub, ctx))
4776 return 0;
4777 }
4778 ADDOP_I(c, BUILD_TUPLE, n);
4779 }
4780 break;
4781 default:
4782 PyErr_Format(PyExc_SystemError,
4783 "invalid subscript kind %d", s->kind);
4784 return 0;
4785 }
4786 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004787}
4788
Thomas Wouters89f507f2006-12-13 04:49:30 +00004789/* End of the compiler section, beginning of the assembler section */
4790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004791/* do depth-first search of basic block graph, starting with block.
4792 post records the block indices in post-order.
4793
4794 XXX must handle implicit jumps from one block to next
4795*/
4796
Thomas Wouters89f507f2006-12-13 04:49:30 +00004797struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 PyObject *a_bytecode; /* string containing bytecode */
4799 int a_offset; /* offset into bytecode */
4800 int a_nblocks; /* number of reachable blocks */
4801 basicblock **a_postorder; /* list of blocks in dfs postorder */
4802 PyObject *a_lnotab; /* string containing lnotab */
4803 int a_lnotab_off; /* offset into lnotab */
4804 int a_lineno; /* last lineno of emitted instruction */
4805 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004806};
4807
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004808static void
4809dfs(struct compiler *c, basicblock *b, struct assembler *a)
4810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 int i;
4812 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 if (b->b_seen)
4815 return;
4816 b->b_seen = 1;
4817 if (b->b_next != NULL)
4818 dfs(c, b->b_next, a);
4819 for (i = 0; i < b->b_iused; i++) {
4820 instr = &b->b_instr[i];
4821 if (instr->i_jrel || instr->i_jabs)
4822 dfs(c, instr->i_target, a);
4823 }
4824 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004825}
4826
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004827static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004828stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4829{
Larry Hastings3a907972013-11-23 14:49:22 -08004830 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 struct instr *instr;
4832 if (b->b_seen || b->b_startdepth >= depth)
4833 return maxdepth;
4834 b->b_seen = 1;
4835 b->b_startdepth = depth;
4836 for (i = 0; i < b->b_iused; i++) {
4837 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004838 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4839 if (effect == PY_INVALID_STACK_EFFECT) {
4840 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4841 Py_FatalError("PyCompile_OpcodeStackEffect()");
4842 }
4843 depth += effect;
4844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 if (depth > maxdepth)
4846 maxdepth = depth;
4847 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4848 if (instr->i_jrel || instr->i_jabs) {
4849 target_depth = depth;
4850 if (instr->i_opcode == FOR_ITER) {
4851 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004852 }
4853 else if (instr->i_opcode == SETUP_FINALLY ||
4854 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 target_depth = depth+3;
4856 if (target_depth > maxdepth)
4857 maxdepth = target_depth;
4858 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004859 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4860 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4861 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 maxdepth = stackdepth_walk(c, instr->i_target,
4863 target_depth, maxdepth);
4864 if (instr->i_opcode == JUMP_ABSOLUTE ||
4865 instr->i_opcode == JUMP_FORWARD) {
4866 goto out; /* remaining code is dead */
4867 }
4868 }
4869 }
4870 if (b->b_next)
4871 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004872out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 b->b_seen = 0;
4874 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004875}
4876
4877/* Find the flow path that needs the largest stack. We assume that
4878 * cycles in the flow graph have no net effect on the stack depth.
4879 */
4880static int
4881stackdepth(struct compiler *c)
4882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 basicblock *b, *entryblock;
4884 entryblock = NULL;
4885 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4886 b->b_seen = 0;
4887 b->b_startdepth = INT_MIN;
4888 entryblock = b;
4889 }
4890 if (!entryblock)
4891 return 0;
4892 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893}
4894
4895static int
4896assemble_init(struct assembler *a, int nblocks, int firstlineno)
4897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 memset(a, 0, sizeof(struct assembler));
4899 a->a_lineno = firstlineno;
4900 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4901 if (!a->a_bytecode)
4902 return 0;
4903 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4904 if (!a->a_lnotab)
4905 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004906 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 PyErr_NoMemory();
4908 return 0;
4909 }
4910 a->a_postorder = (basicblock **)PyObject_Malloc(
4911 sizeof(basicblock *) * nblocks);
4912 if (!a->a_postorder) {
4913 PyErr_NoMemory();
4914 return 0;
4915 }
4916 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004917}
4918
4919static void
4920assemble_free(struct assembler *a)
4921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 Py_XDECREF(a->a_bytecode);
4923 Py_XDECREF(a->a_lnotab);
4924 if (a->a_postorder)
4925 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004926}
4927
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004928static int
4929blocksize(basicblock *b)
4930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 int i;
4932 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004935 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004937}
4938
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004939/* Appends a pair to the end of the line number table, a_lnotab, representing
4940 the instruction's bytecode offset and line number. See
4941 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004942
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004947 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949
Serhiy Storchakaab874002016-09-11 13:48:15 +03004950 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 if(d_bytecode == 0 && d_lineno == 0)
4956 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 if (d_bytecode > 255) {
4959 int j, nbytes, ncodes = d_bytecode / 255;
4960 nbytes = a->a_lnotab_off + 2 * ncodes;
4961 len = PyBytes_GET_SIZE(a->a_lnotab);
4962 if (nbytes >= len) {
4963 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4964 len = nbytes;
4965 else if (len <= INT_MAX / 2)
4966 len *= 2;
4967 else {
4968 PyErr_NoMemory();
4969 return 0;
4970 }
4971 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4972 return 0;
4973 }
4974 lnotab = (unsigned char *)
4975 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4976 for (j = 0; j < ncodes; j++) {
4977 *lnotab++ = 255;
4978 *lnotab++ = 0;
4979 }
4980 d_bytecode -= ncodes * 255;
4981 a->a_lnotab_off += ncodes * 2;
4982 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004983 assert(0 <= d_bytecode && d_bytecode <= 255);
4984
4985 if (d_lineno < -128 || 127 < d_lineno) {
4986 int j, nbytes, ncodes, k;
4987 if (d_lineno < 0) {
4988 k = -128;
4989 /* use division on positive numbers */
4990 ncodes = (-d_lineno) / 128;
4991 }
4992 else {
4993 k = 127;
4994 ncodes = d_lineno / 127;
4995 }
4996 d_lineno -= ncodes * k;
4997 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 nbytes = a->a_lnotab_off + 2 * ncodes;
4999 len = PyBytes_GET_SIZE(a->a_lnotab);
5000 if (nbytes >= len) {
5001 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5002 len = nbytes;
5003 else if (len <= INT_MAX / 2)
5004 len *= 2;
5005 else {
5006 PyErr_NoMemory();
5007 return 0;
5008 }
5009 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5010 return 0;
5011 }
5012 lnotab = (unsigned char *)
5013 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5014 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005015 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 d_bytecode = 0;
5017 for (j = 1; j < ncodes; j++) {
5018 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005019 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 a->a_lnotab_off += ncodes * 2;
5022 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005023 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 len = PyBytes_GET_SIZE(a->a_lnotab);
5026 if (a->a_lnotab_off + 2 >= len) {
5027 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5028 return 0;
5029 }
5030 lnotab = (unsigned char *)
5031 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 a->a_lnotab_off += 2;
5034 if (d_bytecode) {
5035 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005036 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 }
5038 else { /* First line of a block; def stmt, etc. */
5039 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005040 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 }
5042 a->a_lineno = i->i_lineno;
5043 a->a_lineno_off = a->a_offset;
5044 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005045}
5046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005047/* assemble_emit()
5048 Extend the bytecode with a new instruction.
5049 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005050*/
5051
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005052static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005053assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005054{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005055 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005057 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005058
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005059 arg = i->i_oparg;
5060 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 if (i->i_lineno && !assemble_lnotab(a, i))
5062 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005063 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 if (len > PY_SSIZE_T_MAX / 2)
5065 return 0;
5066 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5067 return 0;
5068 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005069 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005071 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005073}
5074
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005075static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005076assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005079 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 /* Compute the size of each block and fixup jump args.
5083 Replace block pointer with position in bytecode. */
5084 do {
5085 totsize = 0;
5086 for (i = a->a_nblocks - 1; i >= 0; i--) {
5087 b = a->a_postorder[i];
5088 bsize = blocksize(b);
5089 b->b_offset = totsize;
5090 totsize += bsize;
5091 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005092 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5094 bsize = b->b_offset;
5095 for (i = 0; i < b->b_iused; i++) {
5096 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005097 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 /* Relative jumps are computed relative to
5099 the instruction pointer after fetching
5100 the jump instruction.
5101 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005102 bsize += isize;
5103 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005105 if (instr->i_jrel) {
5106 instr->i_oparg -= bsize;
5107 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005108 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005109 if (instrsize(instr->i_oparg) != isize) {
5110 extended_arg_recompile = 1;
5111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 }
5114 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 /* XXX: This is an awful hack that could hurt performance, but
5117 on the bright side it should work until we come up
5118 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 The issue is that in the first loop blocksize() is called
5121 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005122 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 So we loop until we stop seeing new EXTENDED_ARGs.
5126 The only EXTENDED_ARGs that could be popping up are
5127 ones in jump instructions. So this should converge
5128 fairly quickly.
5129 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005130 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005131}
5132
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005133static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005134dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005137 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 tuple = PyTuple_New(size);
5140 if (tuple == NULL)
5141 return NULL;
5142 while (PyDict_Next(dict, &pos, &k, &v)) {
5143 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005144 /* The keys of the dictionary are tuples. (see compiler_add_o
5145 * and _PyCode_ConstantKey). The object we want is always second,
5146 * though. */
5147 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 Py_INCREF(k);
5149 assert((i - offset) < size);
5150 assert((i - offset) >= 0);
5151 PyTuple_SET_ITEM(tuple, i - offset, k);
5152 }
5153 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005154}
5155
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005156static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005157compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005160 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005162 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 if (ste->ste_nested)
5164 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005165 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005167 if (!ste->ste_generator && ste->ste_coroutine)
5168 flags |= CO_COROUTINE;
5169 if (ste->ste_generator && ste->ste_coroutine)
5170 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 if (ste->ste_varargs)
5172 flags |= CO_VARARGS;
5173 if (ste->ste_varkeywords)
5174 flags |= CO_VARKEYWORDS;
5175 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 /* (Only) inherit compilerflags in PyCF_MASK */
5178 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005179
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005180 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5181 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5182 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005186}
5187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005188static PyCodeObject *
5189makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 PyObject *tmp;
5192 PyCodeObject *co = NULL;
5193 PyObject *consts = NULL;
5194 PyObject *names = NULL;
5195 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 PyObject *name = NULL;
5197 PyObject *freevars = NULL;
5198 PyObject *cellvars = NULL;
5199 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005200 Py_ssize_t nlocals;
5201 int nlocals_int;
5202 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005203 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 tmp = dict_keys_inorder(c->u->u_consts, 0);
5206 if (!tmp)
5207 goto error;
5208 consts = PySequence_List(tmp); /* optimize_code requires a list */
5209 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 names = dict_keys_inorder(c->u->u_names, 0);
5212 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5213 if (!consts || !names || !varnames)
5214 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5217 if (!cellvars)
5218 goto error;
5219 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5220 if (!freevars)
5221 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005222
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005223 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005224 assert(nlocals < INT_MAX);
5225 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 flags = compute_code_flags(c);
5228 if (flags < 0)
5229 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5232 if (!bytecode)
5233 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5236 if (!tmp)
5237 goto error;
5238 Py_DECREF(consts);
5239 consts = tmp;
5240
Victor Stinnerf8e32212013-11-19 23:56:34 +01005241 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5242 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5243 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005244 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 bytecode, consts, names, varnames,
5246 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005247 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 c->u->u_firstlineno,
5249 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005250 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 Py_XDECREF(consts);
5252 Py_XDECREF(names);
5253 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 Py_XDECREF(name);
5255 Py_XDECREF(freevars);
5256 Py_XDECREF(cellvars);
5257 Py_XDECREF(bytecode);
5258 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005259}
5260
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005261
5262/* For debugging purposes only */
5263#if 0
5264static void
5265dump_instr(const struct instr *i)
5266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 const char *jrel = i->i_jrel ? "jrel " : "";
5268 const char *jabs = i->i_jabs ? "jabs " : "";
5269 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005272 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005274 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5276 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005277}
5278
5279static void
5280dump_basicblock(const basicblock *b)
5281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 const char *seen = b->b_seen ? "seen " : "";
5283 const char *b_return = b->b_return ? "return " : "";
5284 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5285 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5286 if (b->b_instr) {
5287 int i;
5288 for (i = 0; i < b->b_iused; i++) {
5289 fprintf(stderr, " [%02d] ", i);
5290 dump_instr(b->b_instr + i);
5291 }
5292 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005293}
5294#endif
5295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005296static PyCodeObject *
5297assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 basicblock *b, *entryblock;
5300 struct assembler a;
5301 int i, j, nblocks;
5302 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 /* Make sure every block that falls off the end returns None.
5305 XXX NEXT_BLOCK() isn't quite right, because if the last
5306 block ends with a jump or return b_next shouldn't set.
5307 */
5308 if (!c->u->u_curblock->b_return) {
5309 NEXT_BLOCK(c);
5310 if (addNone)
5311 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5312 ADDOP(c, RETURN_VALUE);
5313 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 nblocks = 0;
5316 entryblock = NULL;
5317 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5318 nblocks++;
5319 entryblock = b;
5320 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 /* Set firstlineno if it wasn't explicitly set. */
5323 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005324 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5326 else
5327 c->u->u_firstlineno = 1;
5328 }
5329 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5330 goto error;
5331 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 /* Can't modify the bytecode after computing jump offsets. */
5334 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 /* Emit code in reverse postorder from dfs. */
5337 for (i = a.a_nblocks - 1; i >= 0; i--) {
5338 b = a.a_postorder[i];
5339 for (j = 0; j < b->b_iused; j++)
5340 if (!assemble_emit(&a, &b->b_instr[j]))
5341 goto error;
5342 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5345 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005346 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 assemble_free(&a);
5352 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005353}
Georg Brandl8334fd92010-12-04 10:26:46 +00005354
5355#undef PyAST_Compile
5356PyAPI_FUNC(PyCodeObject *)
5357PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5358 PyArena *arena)
5359{
5360 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5361}