blob: a3ea60d07c01af7fe3f441a75465f4ae64054a7d [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:
Barry Warsawb2e57942017-09-14 18:13:16 -07001353 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001354 }
1355}
1356
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001357/* Search if variable annotations are present statically in a block. */
1358
1359static int
1360find_ann(asdl_seq *stmts)
1361{
1362 int i, j, res = 0;
1363 stmt_ty st;
1364
1365 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1366 st = (stmt_ty)asdl_seq_GET(stmts, i);
1367 switch (st->kind) {
1368 case AnnAssign_kind:
1369 return 1;
1370 case For_kind:
1371 res = find_ann(st->v.For.body) ||
1372 find_ann(st->v.For.orelse);
1373 break;
1374 case AsyncFor_kind:
1375 res = find_ann(st->v.AsyncFor.body) ||
1376 find_ann(st->v.AsyncFor.orelse);
1377 break;
1378 case While_kind:
1379 res = find_ann(st->v.While.body) ||
1380 find_ann(st->v.While.orelse);
1381 break;
1382 case If_kind:
1383 res = find_ann(st->v.If.body) ||
1384 find_ann(st->v.If.orelse);
1385 break;
1386 case With_kind:
1387 res = find_ann(st->v.With.body);
1388 break;
1389 case AsyncWith_kind:
1390 res = find_ann(st->v.AsyncWith.body);
1391 break;
1392 case Try_kind:
1393 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1394 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1395 st->v.Try.handlers, j);
1396 if (find_ann(handler->v.ExceptHandler.body)) {
1397 return 1;
1398 }
1399 }
1400 res = find_ann(st->v.Try.body) ||
1401 find_ann(st->v.Try.finalbody) ||
1402 find_ann(st->v.Try.orelse);
1403 break;
1404 default:
1405 res = 0;
1406 }
1407 if (res) {
1408 break;
1409 }
1410 }
1411 return res;
1412}
1413
1414/* Compile a sequence of statements, checking for a docstring
1415 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416
1417static int
INADA Naokicb41b272017-02-23 00:31:59 +09001418compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001420 /* Set current line number to the line number of first statement.
1421 This way line number for SETUP_ANNOTATIONS will always
1422 coincide with the line number of first "real" statement in module.
1423 If body is empy, then lineno will be set later in assemble. */
1424 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1425 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001426 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001427 c->u->u_lineno = st->lineno;
1428 }
1429 /* Every annotated class and module should have __annotations__. */
1430 if (find_ann(stmts)) {
1431 ADDOP(c, SETUP_ANNOTATIONS);
1432 }
INADA Naokicb41b272017-02-23 00:31:59 +09001433 /* if not -OO mode, set docstring */
1434 if (c->c_optimize < 2 && docstring) {
1435 ADDOP_O(c, LOAD_CONST, docstring, consts);
1436 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 }
INADA Naokicb41b272017-02-23 00:31:59 +09001438 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442static PyCodeObject *
1443compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyCodeObject *co;
1446 int addNone = 1;
1447 static PyObject *module;
1448 if (!module) {
1449 module = PyUnicode_InternFromString("<module>");
1450 if (!module)
1451 return NULL;
1452 }
1453 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001454 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 return NULL;
1456 switch (mod->kind) {
1457 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001458 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 compiler_exit_scope(c);
1460 return 0;
1461 }
1462 break;
1463 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001464 if (find_ann(mod->v.Interactive.body)) {
1465 ADDOP(c, SETUP_ANNOTATIONS);
1466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 c->c_interactive = 1;
1468 VISIT_SEQ_IN_SCOPE(c, stmt,
1469 mod->v.Interactive.body);
1470 break;
1471 case Expression_kind:
1472 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1473 addNone = 0;
1474 break;
1475 case Suite_kind:
1476 PyErr_SetString(PyExc_SystemError,
1477 "suite should not be possible");
1478 return 0;
1479 default:
1480 PyErr_Format(PyExc_SystemError,
1481 "module kind %d should not be possible",
1482 mod->kind);
1483 return 0;
1484 }
1485 co = assemble(c, addNone);
1486 compiler_exit_scope(c);
1487 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490/* The test for LOCAL must come before the test for FREE in order to
1491 handle classes where name is both local and free. The local var is
1492 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001493*/
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495static int
1496get_ref_type(struct compiler *c, PyObject *name)
1497{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001498 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001499 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001500 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001501 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001502 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (scope == 0) {
1504 char buf[350];
1505 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001506 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001508 PyUnicode_AsUTF8(name),
1509 PyUnicode_AsUTF8(c->u->u_name),
1510 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1511 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1512 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1513 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 );
1515 Py_FatalError(buf);
1516 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
1521static int
1522compiler_lookup_arg(PyObject *dict, PyObject *name)
1523{
1524 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001525 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001527 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001529 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001531 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001532 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
1535static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001536compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001538 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001539 if (qualname == NULL)
1540 qualname = co->co_name;
1541
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001542 if (free) {
1543 for (i = 0; i < free; ++i) {
1544 /* Bypass com_addop_varname because it will generate
1545 LOAD_DEREF but LOAD_CLOSURE is needed.
1546 */
1547 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1548 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001549
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001550 /* Special case: If a class contains a method with a
1551 free variable that has the same name as a method,
1552 the name will be considered free *and* local in the
1553 class. It should be handled by the closure, as
1554 well as by the normal name loookup logic.
1555 */
1556 reftype = get_ref_type(c, name);
1557 if (reftype == CELL)
1558 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1559 else /* (reftype == FREE) */
1560 arg = compiler_lookup_arg(c->u->u_freevars, name);
1561 if (arg == -1) {
1562 fprintf(stderr,
1563 "lookup %s in %s %d %d\n"
1564 "freevars of %s: %s\n",
1565 PyUnicode_AsUTF8(PyObject_Repr(name)),
1566 PyUnicode_AsUTF8(c->u->u_name),
1567 reftype, arg,
1568 PyUnicode_AsUTF8(co->co_name),
1569 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1570 Py_FatalError("compiler_make_closure()");
1571 }
1572 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001574 flags |= 0x08;
1575 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001578 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001579 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581}
1582
1583static int
1584compiler_decorators(struct compiler *c, asdl_seq* decos)
1585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (!decos)
1589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1592 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1593 }
1594 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595}
1596
1597static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001598compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001600{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001601 /* Push a dict of keyword-only default values.
1602
1603 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1604 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001605 int i;
1606 PyObject *keys = NULL;
1607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1609 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1610 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1611 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001612 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001613 if (!mangled) {
1614 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001616 if (keys == NULL) {
1617 keys = PyList_New(1);
1618 if (keys == NULL) {
1619 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001620 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001621 }
1622 PyList_SET_ITEM(keys, 0, mangled);
1623 }
1624 else {
1625 int res = PyList_Append(keys, mangled);
1626 Py_DECREF(mangled);
1627 if (res == -1) {
1628 goto error;
1629 }
1630 }
1631 if (!compiler_visit_expr(c, default_)) {
1632 goto error;
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 }
1635 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001636 if (keys != NULL) {
1637 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1638 PyObject *keys_tuple = PyList_AsTuple(keys);
1639 Py_DECREF(keys);
1640 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001641 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001642 }
1643 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1644 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001645 assert(default_count > 0);
1646 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001647 }
1648 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001649 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001650 }
1651
1652error:
1653 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001654 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001655}
1656
1657static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001658compiler_visit_argannotation(struct compiler *c, identifier id,
1659 expr_ty annotation, PyObject *names)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001662 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001664 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001665 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001666 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001667 if (PyList_Append(names, mangled) < 0) {
1668 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001669 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001670 }
1671 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001673 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001674}
1675
1676static int
1677compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1678 PyObject *names)
1679{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001680 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 for (i = 0; i < asdl_seq_LEN(args); i++) {
1682 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001683 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 c,
1685 arg->arg,
1686 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001687 names))
1688 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001690 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001691}
1692
1693static int
1694compiler_visit_annotations(struct compiler *c, arguments_ty args,
1695 expr_ty returns)
1696{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001697 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001698 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001699
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001700 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 */
1702 static identifier return_str;
1703 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001704 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 names = PyList_New(0);
1706 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001707 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001708
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001709 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001711 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001712 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001713 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001715 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001717 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001718 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001719 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (!return_str) {
1723 return_str = PyUnicode_InternFromString("return");
1724 if (!return_str)
1725 goto error;
1726 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001727 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 goto error;
1729 }
1730
1731 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001733 PyObject *keytuple = PyList_AsTuple(names);
1734 Py_DECREF(names);
1735 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001736 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001738 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1739 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001740 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001742 else {
1743 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001744 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001745 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001746
1747error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001749 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001750}
1751
1752static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001753compiler_visit_defaults(struct compiler *c, arguments_ty args)
1754{
1755 VISIT_SEQ(c, expr, args->defaults);
1756 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758}
1759
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001760static Py_ssize_t
1761compiler_default_arguments(struct compiler *c, arguments_ty args)
1762{
1763 Py_ssize_t funcflags = 0;
1764 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 if (!compiler_visit_defaults(c, args))
1766 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001767 funcflags |= 0x01;
1768 }
1769 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001770 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001771 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001772 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001773 return -1;
1774 }
1775 else if (res > 0) {
1776 funcflags |= 0x02;
1777 }
1778 }
1779 return funcflags;
1780}
1781
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782static int
Yury Selivanov75445082015-05-11 22:57:16 -04001783compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001786 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001787 arguments_ty args;
1788 expr_ty returns;
1789 identifier name;
1790 asdl_seq* decos;
1791 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001792 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001793 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001794 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795
Yury Selivanov75445082015-05-11 22:57:16 -04001796 if (is_async) {
1797 assert(s->kind == AsyncFunctionDef_kind);
1798
1799 args = s->v.AsyncFunctionDef.args;
1800 returns = s->v.AsyncFunctionDef.returns;
1801 decos = s->v.AsyncFunctionDef.decorator_list;
1802 name = s->v.AsyncFunctionDef.name;
1803 body = s->v.AsyncFunctionDef.body;
1804
1805 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1806 } else {
1807 assert(s->kind == FunctionDef_kind);
1808
1809 args = s->v.FunctionDef.args;
1810 returns = s->v.FunctionDef.returns;
1811 decos = s->v.FunctionDef.decorator_list;
1812 name = s->v.FunctionDef.name;
1813 body = s->v.FunctionDef.body;
1814
1815 scope_type = COMPILER_SCOPE_FUNCTION;
1816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (!compiler_decorators(c, decos))
1819 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001820
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001821 funcflags = compiler_default_arguments(c, args);
1822 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001824 }
1825
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001826 annotations = compiler_visit_annotations(c, args, returns);
1827 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001828 return 0;
1829 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001830 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001831 funcflags |= 0x04;
1832 }
1833
1834 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1835 return 0;
1836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837
INADA Naokicb41b272017-02-23 00:31:59 +09001838 /* if not -OO mode, add docstring */
1839 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1840 docstring = s->v.FunctionDef.docstring;
1841 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 compiler_exit_scope(c);
1843 return 0;
1844 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 c->u->u_argcount = asdl_seq_LEN(args->args);
1847 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001849 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001851 qualname = c->u->u_qualname;
1852 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001854 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001855 Py_XDECREF(qualname);
1856 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001860 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001861 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* decorators */
1865 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1866 ADDOP_I(c, CALL_FUNCTION, 1);
1867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868
Yury Selivanov75445082015-05-11 22:57:16 -04001869 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870}
1871
1872static int
1873compiler_class(struct compiler *c, stmt_ty s)
1874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 PyCodeObject *co;
1876 PyObject *str;
1877 int i;
1878 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (!compiler_decorators(c, decos))
1881 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* ultimately generate code for:
1884 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1885 where:
1886 <func> is a function/closure created from the class body;
1887 it has a single argument (__locals__) where the dict
1888 (or MutableSequence) representing the locals is passed
1889 <name> is the class name
1890 <bases> is the positional arguments and *varargs argument
1891 <keywords> is the keyword arguments and **kwds argument
1892 This borrows from compiler_call.
1893 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001896 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1897 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return 0;
1899 /* this block represents what we do in the new scope */
1900 {
1901 /* use the class name for name mangling */
1902 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001903 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* load (global) __name__ ... */
1905 str = PyUnicode_InternFromString("__name__");
1906 if (!str || !compiler_nameop(c, str, Load)) {
1907 Py_XDECREF(str);
1908 compiler_exit_scope(c);
1909 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 Py_DECREF(str);
1912 /* ... and store it as __module__ */
1913 str = PyUnicode_InternFromString("__module__");
1914 if (!str || !compiler_nameop(c, str, Store)) {
1915 Py_XDECREF(str);
1916 compiler_exit_scope(c);
1917 return 0;
1918 }
1919 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001920 assert(c->u->u_qualname);
1921 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001922 str = PyUnicode_InternFromString("__qualname__");
1923 if (!str || !compiler_nameop(c, str, Store)) {
1924 Py_XDECREF(str);
1925 compiler_exit_scope(c);
1926 return 0;
1927 }
1928 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001930 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 compiler_exit_scope(c);
1932 return 0;
1933 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001934 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001935 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001936 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001937 str = PyUnicode_InternFromString("__class__");
1938 if (str == NULL) {
1939 compiler_exit_scope(c);
1940 return 0;
1941 }
1942 i = compiler_lookup_arg(c->u->u_cellvars, str);
1943 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001944 if (i < 0) {
1945 compiler_exit_scope(c);
1946 return 0;
1947 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001948 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001951 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001952 str = PyUnicode_InternFromString("__classcell__");
1953 if (!str || !compiler_nameop(c, str, Store)) {
1954 Py_XDECREF(str);
1955 compiler_exit_scope(c);
1956 return 0;
1957 }
1958 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001960 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001961 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001962 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001963 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001964 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001965 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 /* create the code object */
1967 co = assemble(c, 1);
1968 }
1969 /* leave the new scope */
1970 compiler_exit_scope(c);
1971 if (co == NULL)
1972 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* 2. load the 'build_class' function */
1975 ADDOP(c, LOAD_BUILD_CLASS);
1976
1977 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001978 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 Py_DECREF(co);
1980
1981 /* 4. load class name */
1982 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1983
1984 /* 5. generate the rest of the code for the call */
1985 if (!compiler_call_helper(c, 2,
1986 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001987 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return 0;
1989
1990 /* 6. apply decorators */
1991 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1992 ADDOP_I(c, CALL_FUNCTION, 1);
1993 }
1994
1995 /* 7. store into <name> */
1996 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1997 return 0;
1998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999}
2000
2001static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002002cmpop(cmpop_ty op)
2003{
2004 switch (op) {
2005 case Eq:
2006 return PyCmp_EQ;
2007 case NotEq:
2008 return PyCmp_NE;
2009 case Lt:
2010 return PyCmp_LT;
2011 case LtE:
2012 return PyCmp_LE;
2013 case Gt:
2014 return PyCmp_GT;
2015 case GtE:
2016 return PyCmp_GE;
2017 case Is:
2018 return PyCmp_IS;
2019 case IsNot:
2020 return PyCmp_IS_NOT;
2021 case In:
2022 return PyCmp_IN;
2023 case NotIn:
2024 return PyCmp_NOT_IN;
2025 default:
2026 return PyCmp_BAD;
2027 }
2028}
2029
2030static int
2031compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2032{
2033 switch (e->kind) {
2034 case UnaryOp_kind:
2035 if (e->v.UnaryOp.op == Not)
2036 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2037 /* fallback to general implementation */
2038 break;
2039 case BoolOp_kind: {
2040 asdl_seq *s = e->v.BoolOp.values;
2041 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2042 assert(n >= 0);
2043 int cond2 = e->v.BoolOp.op == Or;
2044 basicblock *next2 = next;
2045 if (!cond2 != !cond) {
2046 next2 = compiler_new_block(c);
2047 if (next2 == NULL)
2048 return 0;
2049 }
2050 for (i = 0; i < n; ++i) {
2051 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2052 return 0;
2053 }
2054 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2055 return 0;
2056 if (next2 != next)
2057 compiler_use_next_block(c, next2);
2058 return 1;
2059 }
2060 case IfExp_kind: {
2061 basicblock *end, *next2;
2062 end = compiler_new_block(c);
2063 if (end == NULL)
2064 return 0;
2065 next2 = compiler_new_block(c);
2066 if (next2 == NULL)
2067 return 0;
2068 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2069 return 0;
2070 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2071 return 0;
2072 ADDOP_JREL(c, JUMP_FORWARD, end);
2073 compiler_use_next_block(c, next2);
2074 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2075 return 0;
2076 compiler_use_next_block(c, end);
2077 return 1;
2078 }
2079 case Compare_kind: {
2080 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2081 if (n > 0) {
2082 basicblock *cleanup = compiler_new_block(c);
2083 if (cleanup == NULL)
2084 return 0;
2085 VISIT(c, expr, e->v.Compare.left);
2086 for (i = 0; i < n; i++) {
2087 VISIT(c, expr,
2088 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2089 ADDOP(c, DUP_TOP);
2090 ADDOP(c, ROT_THREE);
2091 ADDOP_I(c, COMPARE_OP,
2092 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2093 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2094 NEXT_BLOCK(c);
2095 }
2096 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2097 ADDOP_I(c, COMPARE_OP,
2098 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2099 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2100 basicblock *end = compiler_new_block(c);
2101 if (end == NULL)
2102 return 0;
2103 ADDOP_JREL(c, JUMP_FORWARD, end);
2104 compiler_use_next_block(c, cleanup);
2105 ADDOP(c, POP_TOP);
2106 if (!cond) {
2107 ADDOP_JREL(c, JUMP_FORWARD, next);
2108 }
2109 compiler_use_next_block(c, end);
2110 return 1;
2111 }
2112 /* fallback to general implementation */
2113 break;
2114 }
2115 default:
2116 /* fallback to general implementation */
2117 break;
2118 }
2119
2120 /* general implementation */
2121 VISIT(c, expr, e);
2122 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2123 return 1;
2124}
2125
2126static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002127compiler_ifexp(struct compiler *c, expr_ty e)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 basicblock *end, *next;
2130
2131 assert(e->kind == IfExp_kind);
2132 end = compiler_new_block(c);
2133 if (end == NULL)
2134 return 0;
2135 next = compiler_new_block(c);
2136 if (next == NULL)
2137 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002138 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2139 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 VISIT(c, expr, e->v.IfExp.body);
2141 ADDOP_JREL(c, JUMP_FORWARD, end);
2142 compiler_use_next_block(c, next);
2143 VISIT(c, expr, e->v.IfExp.orelse);
2144 compiler_use_next_block(c, end);
2145 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002146}
2147
2148static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149compiler_lambda(struct compiler *c, expr_ty e)
2150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002152 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 arguments_ty args = e->v.Lambda.args;
2156 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (!name) {
2159 name = PyUnicode_InternFromString("<lambda>");
2160 if (!name)
2161 return 0;
2162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002164 funcflags = compiler_default_arguments(c, args);
2165 if (funcflags == -1) {
2166 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002168
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002169 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002170 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* Make None the first constant, so the lambda can't have a
2174 docstring. */
2175 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2176 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 c->u->u_argcount = asdl_seq_LEN(args->args);
2179 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2180 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2181 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002182 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
2184 else {
2185 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002186 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002188 qualname = c->u->u_qualname;
2189 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002191 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002194 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002195 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_DECREF(co);
2197
2198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199}
2200
2201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202compiler_if(struct compiler *c, stmt_ty s)
2203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 basicblock *end, *next;
2205 int constant;
2206 assert(s->kind == If_kind);
2207 end = compiler_new_block(c);
2208 if (end == NULL)
2209 return 0;
2210
Georg Brandl8334fd92010-12-04 10:26:46 +00002211 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* constant = 0: "if 0"
2213 * constant = 1: "if 1", "if 2", ...
2214 * constant = -1: rest */
2215 if (constant == 0) {
2216 if (s->v.If.orelse)
2217 VISIT_SEQ(c, stmt, s->v.If.orelse);
2218 } else if (constant == 1) {
2219 VISIT_SEQ(c, stmt, s->v.If.body);
2220 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002221 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 next = compiler_new_block(c);
2223 if (next == NULL)
2224 return 0;
2225 }
2226 else
2227 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002228 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2229 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002231 if (asdl_seq_LEN(s->v.If.orelse)) {
2232 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 compiler_use_next_block(c, next);
2234 VISIT_SEQ(c, stmt, s->v.If.orelse);
2235 }
2236 }
2237 compiler_use_next_block(c, end);
2238 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239}
2240
2241static int
2242compiler_for(struct compiler *c, stmt_ty s)
2243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 start = compiler_new_block(c);
2247 cleanup = compiler_new_block(c);
2248 end = compiler_new_block(c);
2249 if (start == NULL || end == NULL || cleanup == NULL)
2250 return 0;
2251 ADDOP_JREL(c, SETUP_LOOP, end);
2252 if (!compiler_push_fblock(c, LOOP, start))
2253 return 0;
2254 VISIT(c, expr, s->v.For.iter);
2255 ADDOP(c, GET_ITER);
2256 compiler_use_next_block(c, start);
2257 ADDOP_JREL(c, FOR_ITER, cleanup);
2258 VISIT(c, expr, s->v.For.target);
2259 VISIT_SEQ(c, stmt, s->v.For.body);
2260 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2261 compiler_use_next_block(c, cleanup);
2262 ADDOP(c, POP_BLOCK);
2263 compiler_pop_fblock(c, LOOP, start);
2264 VISIT_SEQ(c, stmt, s->v.For.orelse);
2265 compiler_use_next_block(c, end);
2266 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267}
2268
Yury Selivanov75445082015-05-11 22:57:16 -04002269
2270static int
2271compiler_async_for(struct compiler *c, stmt_ty s)
2272{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002273 _Py_IDENTIFIER(StopAsyncIteration);
2274
Yury Selivanov75445082015-05-11 22:57:16 -04002275 basicblock *try, *except, *end, *after_try, *try_cleanup,
2276 *after_loop, *after_loop_else;
2277
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002278 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2279 if (stop_aiter_error == NULL) {
2280 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002281 }
2282
2283 try = compiler_new_block(c);
2284 except = compiler_new_block(c);
2285 end = compiler_new_block(c);
2286 after_try = compiler_new_block(c);
2287 try_cleanup = compiler_new_block(c);
2288 after_loop = compiler_new_block(c);
2289 after_loop_else = compiler_new_block(c);
2290
2291 if (try == NULL || except == NULL || end == NULL
2292 || after_try == NULL || try_cleanup == NULL)
2293 return 0;
2294
2295 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2296 if (!compiler_push_fblock(c, LOOP, try))
2297 return 0;
2298
2299 VISIT(c, expr, s->v.AsyncFor.iter);
2300 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002301
2302 compiler_use_next_block(c, try);
2303
2304
2305 ADDOP_JREL(c, SETUP_EXCEPT, except);
2306 if (!compiler_push_fblock(c, EXCEPT, try))
2307 return 0;
2308
2309 ADDOP(c, GET_ANEXT);
2310 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2311 ADDOP(c, YIELD_FROM);
2312 VISIT(c, expr, s->v.AsyncFor.target);
2313 ADDOP(c, POP_BLOCK);
2314 compiler_pop_fblock(c, EXCEPT, try);
2315 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2316
2317
2318 compiler_use_next_block(c, except);
2319 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002320 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002321 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2322 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2323
2324 ADDOP(c, POP_TOP);
2325 ADDOP(c, POP_TOP);
2326 ADDOP(c, POP_TOP);
2327 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2328 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2329 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2330
2331
2332 compiler_use_next_block(c, try_cleanup);
2333 ADDOP(c, END_FINALLY);
2334
2335 compiler_use_next_block(c, after_try);
2336 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2337 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2338
2339 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2340 compiler_pop_fblock(c, LOOP, try);
2341
2342 compiler_use_next_block(c, after_loop);
2343 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2344
2345 compiler_use_next_block(c, after_loop_else);
2346 VISIT_SEQ(c, stmt, s->v.For.orelse);
2347
2348 compiler_use_next_block(c, end);
2349
2350 return 1;
2351}
2352
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353static int
2354compiler_while(struct compiler *c, stmt_ty s)
2355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002357 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (constant == 0) {
2360 if (s->v.While.orelse)
2361 VISIT_SEQ(c, stmt, s->v.While.orelse);
2362 return 1;
2363 }
2364 loop = compiler_new_block(c);
2365 end = compiler_new_block(c);
2366 if (constant == -1) {
2367 anchor = compiler_new_block(c);
2368 if (anchor == NULL)
2369 return 0;
2370 }
2371 if (loop == NULL || end == NULL)
2372 return 0;
2373 if (s->v.While.orelse) {
2374 orelse = compiler_new_block(c);
2375 if (orelse == NULL)
2376 return 0;
2377 }
2378 else
2379 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 ADDOP_JREL(c, SETUP_LOOP, end);
2382 compiler_use_next_block(c, loop);
2383 if (!compiler_push_fblock(c, LOOP, loop))
2384 return 0;
2385 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002386 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2387 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 }
2389 VISIT_SEQ(c, stmt, s->v.While.body);
2390 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* XXX should the two POP instructions be in a separate block
2393 if there is no else clause ?
2394 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002396 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002398 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 compiler_pop_fblock(c, LOOP, loop);
2400 if (orelse != NULL) /* what if orelse is just pass? */
2401 VISIT_SEQ(c, stmt, s->v.While.orelse);
2402 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405}
2406
2407static int
2408compiler_continue(struct compiler *c)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2411 static const char IN_FINALLY_ERROR_MSG[] =
2412 "'continue' not supported inside 'finally' clause";
2413 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 if (!c->u->u_nfblocks)
2416 return compiler_error(c, LOOP_ERROR_MSG);
2417 i = c->u->u_nfblocks - 1;
2418 switch (c->u->u_fblock[i].fb_type) {
2419 case LOOP:
2420 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2421 break;
2422 case EXCEPT:
2423 case FINALLY_TRY:
2424 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2425 /* Prevent continue anywhere under a finally
2426 even if hidden in a sub-try or except. */
2427 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2428 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2429 }
2430 if (i == -1)
2431 return compiler_error(c, LOOP_ERROR_MSG);
2432 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2433 break;
2434 case FINALLY_END:
2435 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2436 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439}
2440
2441/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442
2443 SETUP_FINALLY L
2444 <code for body>
2445 POP_BLOCK
2446 LOAD_CONST <None>
2447 L: <code for finalbody>
2448 END_FINALLY
2449
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 The special instructions use the block stack. Each block
2451 stack entry contains the instruction that created it (here
2452 SETUP_FINALLY), the level of the value stack at the time the
2453 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 Pushes the current value stack level and the label
2457 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 Pops en entry from the block stack, and pops the value
2460 stack until its level is the same as indicated on the
2461 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Pops a variable number of entries from the *value* stack
2464 and re-raises the exception they specify. The number of
2465 entries popped depends on the (pseudo) exception type.
2466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 The block stack is unwound when an exception is raised:
2468 when a SETUP_FINALLY entry is found, the exception is pushed
2469 onto the value stack (and the exception condition is cleared),
2470 and the interpreter jumps to the label gotten from the block
2471 stack.
2472*/
2473
2474static int
2475compiler_try_finally(struct compiler *c, stmt_ty s)
2476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 basicblock *body, *end;
2478 body = compiler_new_block(c);
2479 end = compiler_new_block(c);
2480 if (body == NULL || end == NULL)
2481 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 ADDOP_JREL(c, SETUP_FINALLY, end);
2484 compiler_use_next_block(c, body);
2485 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2486 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002487 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2488 if (!compiler_try_except(c, s))
2489 return 0;
2490 }
2491 else {
2492 VISIT_SEQ(c, stmt, s->v.Try.body);
2493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 ADDOP(c, POP_BLOCK);
2495 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2498 compiler_use_next_block(c, end);
2499 if (!compiler_push_fblock(c, FINALLY_END, end))
2500 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002501 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 ADDOP(c, END_FINALLY);
2503 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506}
2507
2508/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002509 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 (The contents of the value stack is shown in [], with the top
2511 at the right; 'tb' is trace-back info, 'val' the exception's
2512 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513
2514 Value stack Label Instruction Argument
2515 [] SETUP_EXCEPT L1
2516 [] <code for S>
2517 [] POP_BLOCK
2518 [] JUMP_FORWARD L0
2519
2520 [tb, val, exc] L1: DUP )
2521 [tb, val, exc, exc] <evaluate E1> )
2522 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2523 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2524 [tb, val, exc] POP
2525 [tb, val] <assign to V1> (or POP if no V1)
2526 [tb] POP
2527 [] <code for S1>
2528 JUMP_FORWARD L0
2529
2530 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 .............................etc.......................
2532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2534
2535 [] L0: <next statement>
2536
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 Of course, parts are not generated if Vi or Ei is not present.
2538*/
2539static int
2540compiler_try_except(struct compiler *c, stmt_ty s)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002543 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 body = compiler_new_block(c);
2546 except = compiler_new_block(c);
2547 orelse = compiler_new_block(c);
2548 end = compiler_new_block(c);
2549 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2550 return 0;
2551 ADDOP_JREL(c, SETUP_EXCEPT, except);
2552 compiler_use_next_block(c, body);
2553 if (!compiler_push_fblock(c, EXCEPT, body))
2554 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002555 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 ADDOP(c, POP_BLOCK);
2557 compiler_pop_fblock(c, EXCEPT, body);
2558 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002559 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 compiler_use_next_block(c, except);
2561 for (i = 0; i < n; i++) {
2562 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002563 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (!handler->v.ExceptHandler.type && i < n-1)
2565 return compiler_error(c, "default 'except:' must be last");
2566 c->u->u_lineno_set = 0;
2567 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002568 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 except = compiler_new_block(c);
2570 if (except == NULL)
2571 return 0;
2572 if (handler->v.ExceptHandler.type) {
2573 ADDOP(c, DUP_TOP);
2574 VISIT(c, expr, handler->v.ExceptHandler.type);
2575 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2576 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2577 }
2578 ADDOP(c, POP_TOP);
2579 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002580 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002581
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002582 cleanup_end = compiler_new_block(c);
2583 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002584 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002585 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002586
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002587 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2588 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002590 /*
2591 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002592 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002593 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002594 try:
2595 # body
2596 finally:
2597 name = None
2598 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002599 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002601 /* second try: */
2602 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2603 compiler_use_next_block(c, cleanup_body);
2604 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2605 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002607 /* second # body */
2608 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2609 ADDOP(c, POP_BLOCK);
2610 ADDOP(c, POP_EXCEPT);
2611 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002613 /* finally: */
2614 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2615 compiler_use_next_block(c, cleanup_end);
2616 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2617 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002619 /* name = None */
2620 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2621 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002623 /* del name */
2624 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002626 ADDOP(c, END_FINALLY);
2627 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 }
2629 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002630 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002632 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002633 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002634 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635
Guido van Rossumb940e112007-01-10 16:19:56 +00002636 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002637 ADDOP(c, POP_TOP);
2638 compiler_use_next_block(c, cleanup_body);
2639 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2640 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002642 ADDOP(c, POP_EXCEPT);
2643 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 }
2645 ADDOP_JREL(c, JUMP_FORWARD, end);
2646 compiler_use_next_block(c, except);
2647 }
2648 ADDOP(c, END_FINALLY);
2649 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002650 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 compiler_use_next_block(c, end);
2652 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653}
2654
2655static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002656compiler_try(struct compiler *c, stmt_ty s) {
2657 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2658 return compiler_try_finally(c, s);
2659 else
2660 return compiler_try_except(c, s);
2661}
2662
2663
2664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665compiler_import_as(struct compiler *c, identifier name, identifier asname)
2666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 /* The IMPORT_NAME opcode was already generated. This function
2668 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002671 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002673 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2674 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002675 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002676 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002679 while (1) {
2680 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002682 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002684 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002685 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002687 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002688 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002690 if (dot == -1) {
2691 break;
2692 }
2693 ADDOP(c, ROT_TWO);
2694 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002696 if (!compiler_nameop(c, asname, Store)) {
2697 return 0;
2698 }
2699 ADDOP(c, POP_TOP);
2700 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 }
2702 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703}
2704
2705static int
2706compiler_import(struct compiler *c, stmt_ty s)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 /* The Import node stores a module name like a.b.c as a single
2709 string. This is convenient for all cases except
2710 import a.b.c as d
2711 where we need to parse that string to extract the individual
2712 module names.
2713 XXX Perhaps change the representation to make this case simpler?
2714 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002715 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 for (i = 0; i < n; i++) {
2718 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2719 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002721 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2723 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 if (alias->asname) {
2726 r = compiler_import_as(c, alias->name, alias->asname);
2727 if (!r)
2728 return r;
2729 }
2730 else {
2731 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 Py_ssize_t dot = PyUnicode_FindChar(
2733 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002734 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002736 if (tmp == NULL)
2737 return 0;
2738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 Py_DECREF(tmp);
2742 }
2743 if (!r)
2744 return r;
2745 }
2746 }
2747 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748}
2749
2750static int
2751compiler_from_import(struct compiler *c, stmt_ty s)
2752{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002753 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 PyObject *names = PyTuple_New(n);
2756 PyObject *level;
2757 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 if (!empty_string) {
2760 empty_string = PyUnicode_FromString("");
2761 if (!empty_string)
2762 return 0;
2763 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 if (!names)
2766 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 level = PyLong_FromLong(s->v.ImportFrom.level);
2769 if (!level) {
2770 Py_DECREF(names);
2771 return 0;
2772 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 /* build up the names */
2775 for (i = 0; i < n; i++) {
2776 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2777 Py_INCREF(alias->name);
2778 PyTuple_SET_ITEM(names, i, alias->name);
2779 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002782 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 Py_DECREF(level);
2784 Py_DECREF(names);
2785 return compiler_error(c, "from __future__ imports must occur "
2786 "at the beginning of the file");
2787 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 ADDOP_O(c, LOAD_CONST, level, consts);
2790 Py_DECREF(level);
2791 ADDOP_O(c, LOAD_CONST, names, consts);
2792 Py_DECREF(names);
2793 if (s->v.ImportFrom.module) {
2794 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2795 }
2796 else {
2797 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2798 }
2799 for (i = 0; i < n; i++) {
2800 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2801 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002803 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 assert(n == 1);
2805 ADDOP(c, IMPORT_STAR);
2806 return 1;
2807 }
2808
2809 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2810 store_name = alias->name;
2811 if (alias->asname)
2812 store_name = alias->asname;
2813
2814 if (!compiler_nameop(c, store_name, Store)) {
2815 Py_DECREF(names);
2816 return 0;
2817 }
2818 }
2819 /* remove imported module */
2820 ADDOP(c, POP_TOP);
2821 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822}
2823
2824static int
2825compiler_assert(struct compiler *c, stmt_ty s)
2826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 static PyObject *assertion_error = NULL;
2828 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002829 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Georg Brandl8334fd92010-12-04 10:26:46 +00002831 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 return 1;
2833 if (assertion_error == NULL) {
2834 assertion_error = PyUnicode_InternFromString("AssertionError");
2835 if (assertion_error == NULL)
2836 return 0;
2837 }
2838 if (s->v.Assert.test->kind == Tuple_kind &&
2839 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002840 msg = PyUnicode_FromString("assertion is always true, "
2841 "perhaps remove parentheses?");
2842 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002844 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2845 c->c_filename, c->u->u_lineno,
2846 NULL, NULL) == -1) {
2847 Py_DECREF(msg);
2848 return 0;
2849 }
2850 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 end = compiler_new_block(c);
2853 if (end == NULL)
2854 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002855 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2856 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2858 if (s->v.Assert.msg) {
2859 VISIT(c, expr, s->v.Assert.msg);
2860 ADDOP_I(c, CALL_FUNCTION, 1);
2861 }
2862 ADDOP_I(c, RAISE_VARARGS, 1);
2863 compiler_use_next_block(c, end);
2864 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865}
2866
2867static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002868compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2869{
2870 if (c->c_interactive && c->c_nestlevel <= 1) {
2871 VISIT(c, expr, value);
2872 ADDOP(c, PRINT_EXPR);
2873 return 1;
2874 }
2875
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002876 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002877 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002878 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002879 }
2880
2881 VISIT(c, expr, value);
2882 ADDOP(c, POP_TOP);
2883 return 1;
2884}
2885
2886static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887compiler_visit_stmt(struct compiler *c, stmt_ty s)
2888{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002889 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 /* Always assign a lineno to the next instruction for a stmt. */
2892 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002893 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 switch (s->kind) {
2897 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002898 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 case ClassDef_kind:
2900 return compiler_class(c, s);
2901 case Return_kind:
2902 if (c->u->u_ste->ste_type != FunctionBlock)
2903 return compiler_error(c, "'return' outside function");
2904 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002905 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2906 return compiler_error(
2907 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 VISIT(c, expr, s->v.Return.value);
2909 }
2910 else
2911 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2912 ADDOP(c, RETURN_VALUE);
2913 break;
2914 case Delete_kind:
2915 VISIT_SEQ(c, expr, s->v.Delete.targets)
2916 break;
2917 case Assign_kind:
2918 n = asdl_seq_LEN(s->v.Assign.targets);
2919 VISIT(c, expr, s->v.Assign.value);
2920 for (i = 0; i < n; i++) {
2921 if (i < n - 1)
2922 ADDOP(c, DUP_TOP);
2923 VISIT(c, expr,
2924 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2925 }
2926 break;
2927 case AugAssign_kind:
2928 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002929 case AnnAssign_kind:
2930 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 case For_kind:
2932 return compiler_for(c, s);
2933 case While_kind:
2934 return compiler_while(c, s);
2935 case If_kind:
2936 return compiler_if(c, s);
2937 case Raise_kind:
2938 n = 0;
2939 if (s->v.Raise.exc) {
2940 VISIT(c, expr, s->v.Raise.exc);
2941 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002942 if (s->v.Raise.cause) {
2943 VISIT(c, expr, s->v.Raise.cause);
2944 n++;
2945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002947 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002949 case Try_kind:
2950 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 case Assert_kind:
2952 return compiler_assert(c, s);
2953 case Import_kind:
2954 return compiler_import(c, s);
2955 case ImportFrom_kind:
2956 return compiler_from_import(c, s);
2957 case Global_kind:
2958 case Nonlocal_kind:
2959 break;
2960 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002961 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 case Pass_kind:
2963 break;
2964 case Break_kind:
2965 if (!compiler_in_loop(c))
2966 return compiler_error(c, "'break' outside loop");
2967 ADDOP(c, BREAK_LOOP);
2968 break;
2969 case Continue_kind:
2970 return compiler_continue(c);
2971 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002972 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002973 case AsyncFunctionDef_kind:
2974 return compiler_function(c, s, 1);
2975 case AsyncWith_kind:
2976 return compiler_async_with(c, s, 0);
2977 case AsyncFor_kind:
2978 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 }
Yury Selivanov75445082015-05-11 22:57:16 -04002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
2985unaryop(unaryop_ty op)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 switch (op) {
2988 case Invert:
2989 return UNARY_INVERT;
2990 case Not:
2991 return UNARY_NOT;
2992 case UAdd:
2993 return UNARY_POSITIVE;
2994 case USub:
2995 return UNARY_NEGATIVE;
2996 default:
2997 PyErr_Format(PyExc_SystemError,
2998 "unary op %d should not be possible", op);
2999 return 0;
3000 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001}
3002
3003static int
3004binop(struct compiler *c, operator_ty op)
3005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 switch (op) {
3007 case Add:
3008 return BINARY_ADD;
3009 case Sub:
3010 return BINARY_SUBTRACT;
3011 case Mult:
3012 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003013 case MatMult:
3014 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 case Div:
3016 return BINARY_TRUE_DIVIDE;
3017 case Mod:
3018 return BINARY_MODULO;
3019 case Pow:
3020 return BINARY_POWER;
3021 case LShift:
3022 return BINARY_LSHIFT;
3023 case RShift:
3024 return BINARY_RSHIFT;
3025 case BitOr:
3026 return BINARY_OR;
3027 case BitXor:
3028 return BINARY_XOR;
3029 case BitAnd:
3030 return BINARY_AND;
3031 case FloorDiv:
3032 return BINARY_FLOOR_DIVIDE;
3033 default:
3034 PyErr_Format(PyExc_SystemError,
3035 "binary op %d should not be possible", op);
3036 return 0;
3037 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038}
3039
3040static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041inplace_binop(struct compiler *c, operator_ty op)
3042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 switch (op) {
3044 case Add:
3045 return INPLACE_ADD;
3046 case Sub:
3047 return INPLACE_SUBTRACT;
3048 case Mult:
3049 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003050 case MatMult:
3051 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 case Div:
3053 return INPLACE_TRUE_DIVIDE;
3054 case Mod:
3055 return INPLACE_MODULO;
3056 case Pow:
3057 return INPLACE_POWER;
3058 case LShift:
3059 return INPLACE_LSHIFT;
3060 case RShift:
3061 return INPLACE_RSHIFT;
3062 case BitOr:
3063 return INPLACE_OR;
3064 case BitXor:
3065 return INPLACE_XOR;
3066 case BitAnd:
3067 return INPLACE_AND;
3068 case FloorDiv:
3069 return INPLACE_FLOOR_DIVIDE;
3070 default:
3071 PyErr_Format(PyExc_SystemError,
3072 "inplace binary op %d should not be possible", op);
3073 return 0;
3074 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075}
3076
3077static int
3078compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3079{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003080 int op, scope;
3081 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 PyObject *dict = c->u->u_names;
3085 PyObject *mangled;
3086 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 mangled = _Py_Mangle(c->u->u_private, name);
3089 if (!mangled)
3090 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003091
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003092 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3093 !_PyUnicode_EqualToASCIIString(name, "True") &&
3094 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 op = 0;
3097 optype = OP_NAME;
3098 scope = PyST_GetScope(c->u->u_ste, mangled);
3099 switch (scope) {
3100 case FREE:
3101 dict = c->u->u_freevars;
3102 optype = OP_DEREF;
3103 break;
3104 case CELL:
3105 dict = c->u->u_cellvars;
3106 optype = OP_DEREF;
3107 break;
3108 case LOCAL:
3109 if (c->u->u_ste->ste_type == FunctionBlock)
3110 optype = OP_FAST;
3111 break;
3112 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003113 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 optype = OP_GLOBAL;
3115 break;
3116 case GLOBAL_EXPLICIT:
3117 optype = OP_GLOBAL;
3118 break;
3119 default:
3120 /* scope can be 0 */
3121 break;
3122 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003125 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 switch (optype) {
3128 case OP_DEREF:
3129 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003130 case Load:
3131 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3132 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 case Store: op = STORE_DEREF; break;
3134 case AugLoad:
3135 case AugStore:
3136 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003137 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 case Param:
3139 default:
3140 PyErr_SetString(PyExc_SystemError,
3141 "param invalid for deref variable");
3142 return 0;
3143 }
3144 break;
3145 case OP_FAST:
3146 switch (ctx) {
3147 case Load: op = LOAD_FAST; break;
3148 case Store: op = STORE_FAST; break;
3149 case Del: op = DELETE_FAST; break;
3150 case AugLoad:
3151 case AugStore:
3152 break;
3153 case Param:
3154 default:
3155 PyErr_SetString(PyExc_SystemError,
3156 "param invalid for local variable");
3157 return 0;
3158 }
3159 ADDOP_O(c, op, mangled, varnames);
3160 Py_DECREF(mangled);
3161 return 1;
3162 case OP_GLOBAL:
3163 switch (ctx) {
3164 case Load: op = LOAD_GLOBAL; break;
3165 case Store: op = STORE_GLOBAL; break;
3166 case Del: op = DELETE_GLOBAL; break;
3167 case AugLoad:
3168 case AugStore:
3169 break;
3170 case Param:
3171 default:
3172 PyErr_SetString(PyExc_SystemError,
3173 "param invalid for global variable");
3174 return 0;
3175 }
3176 break;
3177 case OP_NAME:
3178 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003179 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 case Store: op = STORE_NAME; break;
3181 case Del: op = DELETE_NAME; break;
3182 case AugLoad:
3183 case AugStore:
3184 break;
3185 case Param:
3186 default:
3187 PyErr_SetString(PyExc_SystemError,
3188 "param invalid for name variable");
3189 return 0;
3190 }
3191 break;
3192 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 assert(op);
3195 arg = compiler_add_o(c, dict, mangled);
3196 Py_DECREF(mangled);
3197 if (arg < 0)
3198 return 0;
3199 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200}
3201
3202static int
3203compiler_boolop(struct compiler *c, expr_ty e)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003206 int jumpi;
3207 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 assert(e->kind == BoolOp_kind);
3211 if (e->v.BoolOp.op == And)
3212 jumpi = JUMP_IF_FALSE_OR_POP;
3213 else
3214 jumpi = JUMP_IF_TRUE_OR_POP;
3215 end = compiler_new_block(c);
3216 if (end == NULL)
3217 return 0;
3218 s = e->v.BoolOp.values;
3219 n = asdl_seq_LEN(s) - 1;
3220 assert(n >= 0);
3221 for (i = 0; i < n; ++i) {
3222 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3223 ADDOP_JABS(c, jumpi, end);
3224 }
3225 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3226 compiler_use_next_block(c, end);
3227 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228}
3229
3230static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003231starunpack_helper(struct compiler *c, asdl_seq *elts,
3232 int single_op, int inner_op, int outer_op)
3233{
3234 Py_ssize_t n = asdl_seq_LEN(elts);
3235 Py_ssize_t i, nsubitems = 0, nseen = 0;
3236 for (i = 0; i < n; i++) {
3237 expr_ty elt = asdl_seq_GET(elts, i);
3238 if (elt->kind == Starred_kind) {
3239 if (nseen) {
3240 ADDOP_I(c, inner_op, nseen);
3241 nseen = 0;
3242 nsubitems++;
3243 }
3244 VISIT(c, expr, elt->v.Starred.value);
3245 nsubitems++;
3246 }
3247 else {
3248 VISIT(c, expr, elt);
3249 nseen++;
3250 }
3251 }
3252 if (nsubitems) {
3253 if (nseen) {
3254 ADDOP_I(c, inner_op, nseen);
3255 nsubitems++;
3256 }
3257 ADDOP_I(c, outer_op, nsubitems);
3258 }
3259 else
3260 ADDOP_I(c, single_op, nseen);
3261 return 1;
3262}
3263
3264static int
3265assignment_helper(struct compiler *c, asdl_seq *elts)
3266{
3267 Py_ssize_t n = asdl_seq_LEN(elts);
3268 Py_ssize_t i;
3269 int seen_star = 0;
3270 for (i = 0; i < n; i++) {
3271 expr_ty elt = asdl_seq_GET(elts, i);
3272 if (elt->kind == Starred_kind && !seen_star) {
3273 if ((i >= (1 << 8)) ||
3274 (n-i-1 >= (INT_MAX >> 8)))
3275 return compiler_error(c,
3276 "too many expressions in "
3277 "star-unpacking assignment");
3278 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3279 seen_star = 1;
3280 asdl_seq_SET(elts, i, elt->v.Starred.value);
3281 }
3282 else if (elt->kind == Starred_kind) {
3283 return compiler_error(c,
3284 "two starred expressions in assignment");
3285 }
3286 }
3287 if (!seen_star) {
3288 ADDOP_I(c, UNPACK_SEQUENCE, n);
3289 }
3290 VISIT_SEQ(c, expr, elts);
3291 return 1;
3292}
3293
3294static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295compiler_list(struct compiler *c, expr_ty e)
3296{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003297 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003299 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003301 else if (e->v.List.ctx == Load) {
3302 return starunpack_helper(c, elts,
3303 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003305 else
3306 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308}
3309
3310static int
3311compiler_tuple(struct compiler *c, expr_ty e)
3312{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003313 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003315 return assignment_helper(c, elts);
3316 }
3317 else if (e->v.Tuple.ctx == Load) {
3318 return starunpack_helper(c, elts,
3319 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3320 }
3321 else
3322 VISIT_SEQ(c, expr, elts);
3323 return 1;
3324}
3325
3326static int
3327compiler_set(struct compiler *c, expr_ty e)
3328{
3329 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3330 BUILD_SET, BUILD_SET_UNPACK);
3331}
3332
3333static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003334are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3335{
3336 Py_ssize_t i;
3337 for (i = begin; i < end; i++) {
3338 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3339 if (key == NULL || !is_const(key))
3340 return 0;
3341 }
3342 return 1;
3343}
3344
3345static int
3346compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3347{
3348 Py_ssize_t i, n = end - begin;
3349 PyObject *keys, *key;
3350 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3351 for (i = begin; i < end; i++) {
3352 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3353 }
3354 keys = PyTuple_New(n);
3355 if (keys == NULL) {
3356 return 0;
3357 }
3358 for (i = begin; i < end; i++) {
3359 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3360 Py_INCREF(key);
3361 PyTuple_SET_ITEM(keys, i - begin, key);
3362 }
3363 ADDOP_N(c, LOAD_CONST, keys, consts);
3364 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3365 }
3366 else {
3367 for (i = begin; i < end; i++) {
3368 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3369 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3370 }
3371 ADDOP_I(c, BUILD_MAP, n);
3372 }
3373 return 1;
3374}
3375
3376static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003377compiler_dict(struct compiler *c, expr_ty e)
3378{
Victor Stinner976bb402016-03-23 11:36:19 +01003379 Py_ssize_t i, n, elements;
3380 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003381 int is_unpacking = 0;
3382 n = asdl_seq_LEN(e->v.Dict.values);
3383 containers = 0;
3384 elements = 0;
3385 for (i = 0; i < n; i++) {
3386 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3387 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003388 if (!compiler_subdict(c, e, i - elements, i))
3389 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003390 containers++;
3391 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003393 if (is_unpacking) {
3394 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3395 containers++;
3396 }
3397 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003398 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 }
3400 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003401 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003402 if (!compiler_subdict(c, e, n - elements, n))
3403 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003404 containers++;
3405 }
3406 /* If there is more than one dict, they need to be merged into a new
3407 * dict. If there is one dict and it's an unpacking, then it needs
3408 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003409 if (containers > 1 || is_unpacking) {
3410 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 }
3412 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003413}
3414
3415static int
3416compiler_compare(struct compiler *c, expr_ty e)
3417{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003418 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3422 VISIT(c, expr, e->v.Compare.left);
3423 n = asdl_seq_LEN(e->v.Compare.ops);
3424 assert(n > 0);
3425 if (n > 1) {
3426 cleanup = compiler_new_block(c);
3427 if (cleanup == NULL)
3428 return 0;
3429 VISIT(c, expr,
3430 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3431 }
3432 for (i = 1; i < n; i++) {
3433 ADDOP(c, DUP_TOP);
3434 ADDOP(c, ROT_THREE);
3435 ADDOP_I(c, COMPARE_OP,
3436 cmpop((cmpop_ty)(asdl_seq_GET(
3437 e->v.Compare.ops, i - 1))));
3438 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3439 NEXT_BLOCK(c);
3440 if (i < (n - 1))
3441 VISIT(c, expr,
3442 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3443 }
3444 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3445 ADDOP_I(c, COMPARE_OP,
3446 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3447 if (n > 1) {
3448 basicblock *end = compiler_new_block(c);
3449 if (end == NULL)
3450 return 0;
3451 ADDOP_JREL(c, JUMP_FORWARD, end);
3452 compiler_use_next_block(c, cleanup);
3453 ADDOP(c, ROT_TWO);
3454 ADDOP(c, POP_TOP);
3455 compiler_use_next_block(c, end);
3456 }
3457 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458}
3459
3460static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003461maybe_optimize_method_call(struct compiler *c, expr_ty e)
3462{
3463 Py_ssize_t argsl, i;
3464 expr_ty meth = e->v.Call.func;
3465 asdl_seq *args = e->v.Call.args;
3466
3467 /* Check that the call node is an attribute access, and that
3468 the call doesn't have keyword parameters. */
3469 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3470 asdl_seq_LEN(e->v.Call.keywords))
3471 return -1;
3472
3473 /* Check that there are no *varargs types of arguments. */
3474 argsl = asdl_seq_LEN(args);
3475 for (i = 0; i < argsl; i++) {
3476 expr_ty elt = asdl_seq_GET(args, i);
3477 if (elt->kind == Starred_kind) {
3478 return -1;
3479 }
3480 }
3481
3482 /* Alright, we can optimize the code. */
3483 VISIT(c, expr, meth->v.Attribute.value);
3484 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3485 VISIT_SEQ(c, expr, e->v.Call.args);
3486 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3487 return 1;
3488}
3489
3490static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491compiler_call(struct compiler *c, expr_ty e)
3492{
Yury Selivanovf2392132016-12-13 19:03:51 -05003493 if (maybe_optimize_method_call(c, e) > 0)
3494 return 1;
3495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 VISIT(c, expr, e->v.Call.func);
3497 return compiler_call_helper(c, 0,
3498 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003499 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003500}
3501
Eric V. Smith235a6f02015-09-19 14:51:32 -04003502static int
3503compiler_joined_str(struct compiler *c, expr_ty e)
3504{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003505 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003506 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3507 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003508 return 1;
3509}
3510
Eric V. Smitha78c7952015-11-03 12:45:05 -05003511/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003512static int
3513compiler_formatted_value(struct compiler *c, expr_ty e)
3514{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003515 /* Our oparg encodes 2 pieces of information: the conversion
3516 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003517
Eric V. Smitha78c7952015-11-03 12:45:05 -05003518 Convert the conversion char to 2 bits:
3519 None: 000 0x0 FVC_NONE
3520 !s : 001 0x1 FVC_STR
3521 !r : 010 0x2 FVC_REPR
3522 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003523
Eric V. Smitha78c7952015-11-03 12:45:05 -05003524 next bit is whether or not we have a format spec:
3525 yes : 100 0x4
3526 no : 000 0x0
3527 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003528
Eric V. Smitha78c7952015-11-03 12:45:05 -05003529 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003530
Eric V. Smitha78c7952015-11-03 12:45:05 -05003531 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003532 VISIT(c, expr, e->v.FormattedValue.value);
3533
Eric V. Smitha78c7952015-11-03 12:45:05 -05003534 switch (e->v.FormattedValue.conversion) {
3535 case 's': oparg = FVC_STR; break;
3536 case 'r': oparg = FVC_REPR; break;
3537 case 'a': oparg = FVC_ASCII; break;
3538 case -1: oparg = FVC_NONE; break;
3539 default:
3540 PyErr_SetString(PyExc_SystemError,
3541 "Unrecognized conversion character");
3542 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003543 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003544 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003545 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003546 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003547 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003548 }
3549
Eric V. Smitha78c7952015-11-03 12:45:05 -05003550 /* And push our opcode and oparg */
3551 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003552 return 1;
3553}
3554
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003555static int
3556compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3557{
3558 Py_ssize_t i, n = end - begin;
3559 keyword_ty kw;
3560 PyObject *keys, *key;
3561 assert(n > 0);
3562 if (n > 1) {
3563 for (i = begin; i < end; i++) {
3564 kw = asdl_seq_GET(keywords, i);
3565 VISIT(c, expr, kw->value);
3566 }
3567 keys = PyTuple_New(n);
3568 if (keys == NULL) {
3569 return 0;
3570 }
3571 for (i = begin; i < end; i++) {
3572 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3573 Py_INCREF(key);
3574 PyTuple_SET_ITEM(keys, i - begin, key);
3575 }
3576 ADDOP_N(c, LOAD_CONST, keys, consts);
3577 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3578 }
3579 else {
3580 /* a for loop only executes once */
3581 for (i = begin; i < end; i++) {
3582 kw = asdl_seq_GET(keywords, i);
3583 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3584 VISIT(c, expr, kw->value);
3585 }
3586 ADDOP_I(c, BUILD_MAP, n);
3587 }
3588 return 1;
3589}
3590
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003591/* shared code between compiler_call and compiler_class */
3592static int
3593compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003594 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003595 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003596 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003597{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003598 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003599 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003600
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003601 /* the number of tuples and dictionaries on the stack */
3602 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3603
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003604 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003605 nkwelts = asdl_seq_LEN(keywords);
3606
3607 for (i = 0; i < nkwelts; i++) {
3608 keyword_ty kw = asdl_seq_GET(keywords, i);
3609 if (kw->arg == NULL) {
3610 mustdictunpack = 1;
3611 break;
3612 }
3613 }
3614
3615 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003616 for (i = 0; i < nelts; i++) {
3617 expr_ty elt = asdl_seq_GET(args, i);
3618 if (elt->kind == Starred_kind) {
3619 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003620 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003621 if (nseen) {
3622 ADDOP_I(c, BUILD_TUPLE, nseen);
3623 nseen = 0;
3624 nsubargs++;
3625 }
3626 VISIT(c, expr, elt->v.Starred.value);
3627 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003628 }
3629 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003630 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003631 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003634
3635 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003636 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003637 if (nseen) {
3638 /* Pack up any trailing positional arguments. */
3639 ADDOP_I(c, BUILD_TUPLE, nseen);
3640 nsubargs++;
3641 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003642 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003643 /* If we ended up with more than one stararg, we need
3644 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003645 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003646 }
3647 else if (nsubargs == 0) {
3648 ADDOP_I(c, BUILD_TUPLE, 0);
3649 }
3650 nseen = 0; /* the number of keyword arguments on the stack following */
3651 for (i = 0; i < nkwelts; i++) {
3652 keyword_ty kw = asdl_seq_GET(keywords, i);
3653 if (kw->arg == NULL) {
3654 /* A keyword argument unpacking. */
3655 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003656 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3657 return 0;
3658 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003659 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003660 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003661 VISIT(c, expr, kw->value);
3662 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003663 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003664 else {
3665 nseen++;
3666 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003667 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003668 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003669 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003670 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003671 return 0;
3672 nsubkwargs++;
3673 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003674 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003675 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003676 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003677 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003678 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3679 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003681 else if (nkwelts) {
3682 PyObject *names;
3683 VISIT_SEQ(c, keyword, keywords);
3684 names = PyTuple_New(nkwelts);
3685 if (names == NULL) {
3686 return 0;
3687 }
3688 for (i = 0; i < nkwelts; i++) {
3689 keyword_ty kw = asdl_seq_GET(keywords, i);
3690 Py_INCREF(kw->arg);
3691 PyTuple_SET_ITEM(names, i, kw->arg);
3692 }
3693 ADDOP_N(c, LOAD_CONST, names, consts);
3694 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3695 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003697 else {
3698 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3699 return 1;
3700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701}
3702
Nick Coghlan650f0d02007-04-15 12:05:43 +00003703
3704/* List and set comprehensions and generator expressions work by creating a
3705 nested function to perform the actual iteration. This means that the
3706 iteration variables don't leak into the current scope.
3707 The defined function is called immediately following its definition, with the
3708 result of that call being the result of the expression.
3709 The LC/SC version returns the populated container, while the GE version is
3710 flagged in symtable.c as a generator, so it returns the generator object
3711 when the function is called.
3712 This code *knows* that the loop cannot contain break, continue, or return,
3713 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3714
3715 Possible cleanups:
3716 - iterate over the generator sequence instead of using recursion
3717*/
3718
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721compiler_comprehension_generator(struct compiler *c,
3722 asdl_seq *generators, int gen_index,
3723 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003725 comprehension_ty gen;
3726 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3727 if (gen->is_async) {
3728 return compiler_async_comprehension_generator(
3729 c, generators, gen_index, elt, val, type);
3730 } else {
3731 return compiler_sync_comprehension_generator(
3732 c, generators, gen_index, elt, val, type);
3733 }
3734}
3735
3736static int
3737compiler_sync_comprehension_generator(struct compiler *c,
3738 asdl_seq *generators, int gen_index,
3739 expr_ty elt, expr_ty val, int type)
3740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 /* generate code for the iterator, then each of the ifs,
3742 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 comprehension_ty gen;
3745 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003746 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 start = compiler_new_block(c);
3749 skip = compiler_new_block(c);
3750 if_cleanup = compiler_new_block(c);
3751 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3754 anchor == NULL)
3755 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 if (gen_index == 0) {
3760 /* Receive outermost iter as an implicit argument */
3761 c->u->u_argcount = 1;
3762 ADDOP_I(c, LOAD_FAST, 0);
3763 }
3764 else {
3765 /* Sub-iter - calculate on the fly */
3766 VISIT(c, expr, gen->iter);
3767 ADDOP(c, GET_ITER);
3768 }
3769 compiler_use_next_block(c, start);
3770 ADDOP_JREL(c, FOR_ITER, anchor);
3771 NEXT_BLOCK(c);
3772 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 /* XXX this needs to be cleaned up...a lot! */
3775 n = asdl_seq_LEN(gen->ifs);
3776 for (i = 0; i < n; i++) {
3777 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003778 if (!compiler_jump_if(c, e, if_cleanup, 0))
3779 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 NEXT_BLOCK(c);
3781 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 if (++gen_index < asdl_seq_LEN(generators))
3784 if (!compiler_comprehension_generator(c,
3785 generators, gen_index,
3786 elt, val, type))
3787 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 /* only append after the last for generator */
3790 if (gen_index >= asdl_seq_LEN(generators)) {
3791 /* comprehension specific code */
3792 switch (type) {
3793 case COMP_GENEXP:
3794 VISIT(c, expr, elt);
3795 ADDOP(c, YIELD_VALUE);
3796 ADDOP(c, POP_TOP);
3797 break;
3798 case COMP_LISTCOMP:
3799 VISIT(c, expr, elt);
3800 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3801 break;
3802 case COMP_SETCOMP:
3803 VISIT(c, expr, elt);
3804 ADDOP_I(c, SET_ADD, gen_index + 1);
3805 break;
3806 case COMP_DICTCOMP:
3807 /* With 'd[k] = v', v is evaluated before k, so we do
3808 the same. */
3809 VISIT(c, expr, val);
3810 VISIT(c, expr, elt);
3811 ADDOP_I(c, MAP_ADD, gen_index + 1);
3812 break;
3813 default:
3814 return 0;
3815 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 compiler_use_next_block(c, skip);
3818 }
3819 compiler_use_next_block(c, if_cleanup);
3820 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3821 compiler_use_next_block(c, anchor);
3822
3823 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824}
3825
3826static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003827compiler_async_comprehension_generator(struct compiler *c,
3828 asdl_seq *generators, int gen_index,
3829 expr_ty elt, expr_ty val, int type)
3830{
3831 _Py_IDENTIFIER(StopAsyncIteration);
3832
3833 comprehension_ty gen;
3834 basicblock *anchor, *skip, *if_cleanup, *try,
3835 *after_try, *except, *try_cleanup;
3836 Py_ssize_t i, n;
3837
3838 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3839 if (stop_aiter_error == NULL) {
3840 return 0;
3841 }
3842
3843 try = compiler_new_block(c);
3844 after_try = compiler_new_block(c);
3845 try_cleanup = compiler_new_block(c);
3846 except = compiler_new_block(c);
3847 skip = compiler_new_block(c);
3848 if_cleanup = compiler_new_block(c);
3849 anchor = compiler_new_block(c);
3850
3851 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3852 try == NULL || after_try == NULL ||
3853 except == NULL || after_try == NULL) {
3854 return 0;
3855 }
3856
3857 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3858
3859 if (gen_index == 0) {
3860 /* Receive outermost iter as an implicit argument */
3861 c->u->u_argcount = 1;
3862 ADDOP_I(c, LOAD_FAST, 0);
3863 }
3864 else {
3865 /* Sub-iter - calculate on the fly */
3866 VISIT(c, expr, gen->iter);
3867 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003868 }
3869
3870 compiler_use_next_block(c, try);
3871
3872
3873 ADDOP_JREL(c, SETUP_EXCEPT, except);
3874 if (!compiler_push_fblock(c, EXCEPT, try))
3875 return 0;
3876
3877 ADDOP(c, GET_ANEXT);
3878 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3879 ADDOP(c, YIELD_FROM);
3880 VISIT(c, expr, gen->target);
3881 ADDOP(c, POP_BLOCK);
3882 compiler_pop_fblock(c, EXCEPT, try);
3883 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3884
3885
3886 compiler_use_next_block(c, except);
3887 ADDOP(c, DUP_TOP);
3888 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3889 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3890 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3891
3892 ADDOP(c, POP_TOP);
3893 ADDOP(c, POP_TOP);
3894 ADDOP(c, POP_TOP);
3895 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3896 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3897
3898
3899 compiler_use_next_block(c, try_cleanup);
3900 ADDOP(c, END_FINALLY);
3901
3902 compiler_use_next_block(c, after_try);
3903
3904 n = asdl_seq_LEN(gen->ifs);
3905 for (i = 0; i < n; i++) {
3906 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003907 if (!compiler_jump_if(c, e, if_cleanup, 0))
3908 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003909 NEXT_BLOCK(c);
3910 }
3911
3912 if (++gen_index < asdl_seq_LEN(generators))
3913 if (!compiler_comprehension_generator(c,
3914 generators, gen_index,
3915 elt, val, type))
3916 return 0;
3917
3918 /* only append after the last for generator */
3919 if (gen_index >= asdl_seq_LEN(generators)) {
3920 /* comprehension specific code */
3921 switch (type) {
3922 case COMP_GENEXP:
3923 VISIT(c, expr, elt);
3924 ADDOP(c, YIELD_VALUE);
3925 ADDOP(c, POP_TOP);
3926 break;
3927 case COMP_LISTCOMP:
3928 VISIT(c, expr, elt);
3929 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3930 break;
3931 case COMP_SETCOMP:
3932 VISIT(c, expr, elt);
3933 ADDOP_I(c, SET_ADD, gen_index + 1);
3934 break;
3935 case COMP_DICTCOMP:
3936 /* With 'd[k] = v', v is evaluated before k, so we do
3937 the same. */
3938 VISIT(c, expr, val);
3939 VISIT(c, expr, elt);
3940 ADDOP_I(c, MAP_ADD, gen_index + 1);
3941 break;
3942 default:
3943 return 0;
3944 }
3945
3946 compiler_use_next_block(c, skip);
3947 }
3948 compiler_use_next_block(c, if_cleanup);
3949 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3950 compiler_use_next_block(c, anchor);
3951 ADDOP(c, POP_TOP);
3952
3953 return 1;
3954}
3955
3956static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003957compiler_comprehension(struct compiler *c, expr_ty e, int type,
3958 identifier name, asdl_seq *generators, expr_ty elt,
3959 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003962 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003963 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003964 int is_async_function = c->u->u_ste->ste_coroutine;
3965 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003966
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003968
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003969 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3970 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003971 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003973 }
3974
3975 is_async_generator = c->u->u_ste->ste_coroutine;
3976
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04003977 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978 if (e->lineno > c->u->u_lineno) {
3979 c->u->u_lineno = e->lineno;
3980 c->u->u_lineno_set = 0;
3981 }
3982 compiler_error(c, "asynchronous comprehension outside of "
3983 "an asynchronous function");
3984 goto error_in_scope;
3985 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 if (type != COMP_GENEXP) {
3988 int op;
3989 switch (type) {
3990 case COMP_LISTCOMP:
3991 op = BUILD_LIST;
3992 break;
3993 case COMP_SETCOMP:
3994 op = BUILD_SET;
3995 break;
3996 case COMP_DICTCOMP:
3997 op = BUILD_MAP;
3998 break;
3999 default:
4000 PyErr_Format(PyExc_SystemError,
4001 "unknown comprehension type %d", type);
4002 goto error_in_scope;
4003 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 ADDOP_I(c, op, 0);
4006 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 if (!compiler_comprehension_generator(c, generators, 0, elt,
4009 val, type))
4010 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 if (type != COMP_GENEXP) {
4013 ADDOP(c, RETURN_VALUE);
4014 }
4015
4016 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004017 qualname = c->u->u_qualname;
4018 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004020 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 goto error;
4022
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004023 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004025 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 Py_DECREF(co);
4027
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004028 VISIT(c, expr, outermost->iter);
4029
4030 if (outermost->is_async) {
4031 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004032 } else {
4033 ADDOP(c, GET_ITER);
4034 }
4035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004037
4038 if (is_async_generator && type != COMP_GENEXP) {
4039 ADDOP(c, GET_AWAITABLE);
4040 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4041 ADDOP(c, YIELD_FROM);
4042 }
4043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004045error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004047error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004048 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 Py_XDECREF(co);
4050 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004051}
4052
4053static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004054compiler_genexp(struct compiler *c, expr_ty e)
4055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 static identifier name;
4057 if (!name) {
4058 name = PyUnicode_FromString("<genexpr>");
4059 if (!name)
4060 return 0;
4061 }
4062 assert(e->kind == GeneratorExp_kind);
4063 return compiler_comprehension(c, e, COMP_GENEXP, name,
4064 e->v.GeneratorExp.generators,
4065 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066}
4067
4068static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004069compiler_listcomp(struct compiler *c, expr_ty e)
4070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 static identifier name;
4072 if (!name) {
4073 name = PyUnicode_FromString("<listcomp>");
4074 if (!name)
4075 return 0;
4076 }
4077 assert(e->kind == ListComp_kind);
4078 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4079 e->v.ListComp.generators,
4080 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004081}
4082
4083static int
4084compiler_setcomp(struct compiler *c, expr_ty e)
4085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 static identifier name;
4087 if (!name) {
4088 name = PyUnicode_FromString("<setcomp>");
4089 if (!name)
4090 return 0;
4091 }
4092 assert(e->kind == SetComp_kind);
4093 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4094 e->v.SetComp.generators,
4095 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004096}
4097
4098
4099static int
4100compiler_dictcomp(struct compiler *c, expr_ty e)
4101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 static identifier name;
4103 if (!name) {
4104 name = PyUnicode_FromString("<dictcomp>");
4105 if (!name)
4106 return 0;
4107 }
4108 assert(e->kind == DictComp_kind);
4109 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4110 e->v.DictComp.generators,
4111 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004112}
4113
4114
4115static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116compiler_visit_keyword(struct compiler *c, keyword_ty k)
4117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 VISIT(c, expr, k->value);
4119 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120}
4121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 whether they are true or false.
4124
4125 Return values: 1 for true, 0 for false, -1 for non-constant.
4126 */
4127
4128static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004129expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004131 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 switch (e->kind) {
4133 case Ellipsis_kind:
4134 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004135 case Constant_kind:
4136 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 case Num_kind:
4138 return PyObject_IsTrue(e->v.Num.n);
4139 case Str_kind:
4140 return PyObject_IsTrue(e->v.Str.s);
4141 case Name_kind:
4142 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004143 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004144 if (id && strcmp(id, "__debug__") == 0)
4145 return !c->c_optimize;
4146 return -1;
4147 case NameConstant_kind: {
4148 PyObject *o = e->v.NameConstant.value;
4149 if (o == Py_None)
4150 return 0;
4151 else if (o == Py_True)
4152 return 1;
4153 else if (o == Py_False)
4154 return 0;
4155 }
Stefan Krahf432a322017-08-21 13:09:59 +02004156 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 default:
4158 return -1;
4159 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160}
4161
Yury Selivanov75445082015-05-11 22:57:16 -04004162
4163/*
4164 Implements the async with statement.
4165
4166 The semantics outlined in that PEP are as follows:
4167
4168 async with EXPR as VAR:
4169 BLOCK
4170
4171 It is implemented roughly as:
4172
4173 context = EXPR
4174 exit = context.__aexit__ # not calling it
4175 value = await context.__aenter__()
4176 try:
4177 VAR = value # if VAR present in the syntax
4178 BLOCK
4179 finally:
4180 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004181 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004182 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004183 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004184 if not (await exit(*exc)):
4185 raise
4186 */
4187static int
4188compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4189{
4190 basicblock *block, *finally;
4191 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4192
4193 assert(s->kind == AsyncWith_kind);
4194
4195 block = compiler_new_block(c);
4196 finally = compiler_new_block(c);
4197 if (!block || !finally)
4198 return 0;
4199
4200 /* Evaluate EXPR */
4201 VISIT(c, expr, item->context_expr);
4202
4203 ADDOP(c, BEFORE_ASYNC_WITH);
4204 ADDOP(c, GET_AWAITABLE);
4205 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4206 ADDOP(c, YIELD_FROM);
4207
4208 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4209
4210 /* SETUP_ASYNC_WITH pushes a finally block. */
4211 compiler_use_next_block(c, block);
4212 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4213 return 0;
4214 }
4215
4216 if (item->optional_vars) {
4217 VISIT(c, expr, item->optional_vars);
4218 }
4219 else {
4220 /* Discard result from context.__aenter__() */
4221 ADDOP(c, POP_TOP);
4222 }
4223
4224 pos++;
4225 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4226 /* BLOCK code */
4227 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4228 else if (!compiler_async_with(c, s, pos))
4229 return 0;
4230
4231 /* End of try block; start the finally block */
4232 ADDOP(c, POP_BLOCK);
4233 compiler_pop_fblock(c, FINALLY_TRY, block);
4234
4235 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4236 compiler_use_next_block(c, finally);
4237 if (!compiler_push_fblock(c, FINALLY_END, finally))
4238 return 0;
4239
4240 /* Finally block starts; context.__exit__ is on the stack under
4241 the exception or return information. Just issue our magic
4242 opcode. */
4243 ADDOP(c, WITH_CLEANUP_START);
4244
4245 ADDOP(c, GET_AWAITABLE);
4246 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4247 ADDOP(c, YIELD_FROM);
4248
4249 ADDOP(c, WITH_CLEANUP_FINISH);
4250
4251 /* Finally block ends. */
4252 ADDOP(c, END_FINALLY);
4253 compiler_pop_fblock(c, FINALLY_END, finally);
4254 return 1;
4255}
4256
4257
Guido van Rossumc2e20742006-02-27 22:32:47 +00004258/*
4259 Implements the with statement from PEP 343.
4260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004262
4263 with EXPR as VAR:
4264 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265
Guido van Rossumc2e20742006-02-27 22:32:47 +00004266 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267
Thomas Wouters477c8d52006-05-27 19:21:47 +00004268 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004269 exit = context.__exit__ # not calling it
4270 value = context.__enter__()
4271 try:
4272 VAR = value # if VAR present in the syntax
4273 BLOCK
4274 finally:
4275 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004276 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004277 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004278 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004279 exit(*exc)
4280 */
4281static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004282compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004283{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004284 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004285 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004286
4287 assert(s->kind == With_kind);
4288
Guido van Rossumc2e20742006-02-27 22:32:47 +00004289 block = compiler_new_block(c);
4290 finally = compiler_new_block(c);
4291 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004292 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004293
Thomas Wouters477c8d52006-05-27 19:21:47 +00004294 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004295 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004296 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004297
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004298 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004299 compiler_use_next_block(c, block);
4300 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004301 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004302 }
4303
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004304 if (item->optional_vars) {
4305 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004306 }
4307 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004309 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004310 }
4311
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004312 pos++;
4313 if (pos == asdl_seq_LEN(s->v.With.items))
4314 /* BLOCK code */
4315 VISIT_SEQ(c, stmt, s->v.With.body)
4316 else if (!compiler_with(c, s, pos))
4317 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004318
4319 /* End of try block; start the finally block */
4320 ADDOP(c, POP_BLOCK);
4321 compiler_pop_fblock(c, FINALLY_TRY, block);
4322
4323 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4324 compiler_use_next_block(c, finally);
4325 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004326 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004327
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004328 /* Finally block starts; context.__exit__ is on the stack under
4329 the exception or return information. Just issue our magic
4330 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004331 ADDOP(c, WITH_CLEANUP_START);
4332 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004333
4334 /* Finally block ends. */
4335 ADDOP(c, END_FINALLY);
4336 compiler_pop_fblock(c, FINALLY_END, finally);
4337 return 1;
4338}
4339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340static int
4341compiler_visit_expr(struct compiler *c, expr_ty e)
4342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* If expr e has a different line number than the last expr/stmt,
4344 set a new line number for the next instruction.
4345 */
4346 if (e->lineno > c->u->u_lineno) {
4347 c->u->u_lineno = e->lineno;
4348 c->u->u_lineno_set = 0;
4349 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004350 /* Updating the column offset is always harmless. */
4351 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 switch (e->kind) {
4353 case BoolOp_kind:
4354 return compiler_boolop(c, e);
4355 case BinOp_kind:
4356 VISIT(c, expr, e->v.BinOp.left);
4357 VISIT(c, expr, e->v.BinOp.right);
4358 ADDOP(c, binop(c, e->v.BinOp.op));
4359 break;
4360 case UnaryOp_kind:
4361 VISIT(c, expr, e->v.UnaryOp.operand);
4362 ADDOP(c, unaryop(e->v.UnaryOp.op));
4363 break;
4364 case Lambda_kind:
4365 return compiler_lambda(c, e);
4366 case IfExp_kind:
4367 return compiler_ifexp(c, e);
4368 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004369 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004371 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 case GeneratorExp_kind:
4373 return compiler_genexp(c, e);
4374 case ListComp_kind:
4375 return compiler_listcomp(c, e);
4376 case SetComp_kind:
4377 return compiler_setcomp(c, e);
4378 case DictComp_kind:
4379 return compiler_dictcomp(c, e);
4380 case Yield_kind:
4381 if (c->u->u_ste->ste_type != FunctionBlock)
4382 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004383 if (e->v.Yield.value) {
4384 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 }
4386 else {
4387 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4388 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004389 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004391 case YieldFrom_kind:
4392 if (c->u->u_ste->ste_type != FunctionBlock)
4393 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004394
4395 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4396 return compiler_error(c, "'yield from' inside async function");
4397
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004398 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004399 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004400 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4401 ADDOP(c, YIELD_FROM);
4402 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004403 case Await_kind:
4404 if (c->u->u_ste->ste_type != FunctionBlock)
4405 return compiler_error(c, "'await' outside function");
4406
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004407 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4408 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004409 return compiler_error(c, "'await' outside async function");
4410
4411 VISIT(c, expr, e->v.Await.value);
4412 ADDOP(c, GET_AWAITABLE);
4413 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4414 ADDOP(c, YIELD_FROM);
4415 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 case Compare_kind:
4417 return compiler_compare(c, e);
4418 case Call_kind:
4419 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004420 case Constant_kind:
4421 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4422 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 case Num_kind:
4424 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4425 break;
4426 case Str_kind:
4427 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4428 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004429 case JoinedStr_kind:
4430 return compiler_joined_str(c, e);
4431 case FormattedValue_kind:
4432 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 case Bytes_kind:
4434 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4435 break;
4436 case Ellipsis_kind:
4437 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4438 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004439 case NameConstant_kind:
4440 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4441 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* The following exprs can be assignment targets. */
4443 case Attribute_kind:
4444 if (e->v.Attribute.ctx != AugStore)
4445 VISIT(c, expr, e->v.Attribute.value);
4446 switch (e->v.Attribute.ctx) {
4447 case AugLoad:
4448 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004449 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 case Load:
4451 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4452 break;
4453 case AugStore:
4454 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004455 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 case Store:
4457 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4458 break;
4459 case Del:
4460 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4461 break;
4462 case Param:
4463 default:
4464 PyErr_SetString(PyExc_SystemError,
4465 "param invalid in attribute expression");
4466 return 0;
4467 }
4468 break;
4469 case Subscript_kind:
4470 switch (e->v.Subscript.ctx) {
4471 case AugLoad:
4472 VISIT(c, expr, e->v.Subscript.value);
4473 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4474 break;
4475 case Load:
4476 VISIT(c, expr, e->v.Subscript.value);
4477 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4478 break;
4479 case AugStore:
4480 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4481 break;
4482 case Store:
4483 VISIT(c, expr, e->v.Subscript.value);
4484 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4485 break;
4486 case Del:
4487 VISIT(c, expr, e->v.Subscript.value);
4488 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4489 break;
4490 case Param:
4491 default:
4492 PyErr_SetString(PyExc_SystemError,
4493 "param invalid in subscript expression");
4494 return 0;
4495 }
4496 break;
4497 case Starred_kind:
4498 switch (e->v.Starred.ctx) {
4499 case Store:
4500 /* In all legitimate cases, the Starred node was already replaced
4501 * by compiler_list/compiler_tuple. XXX: is that okay? */
4502 return compiler_error(c,
4503 "starred assignment target must be in a list or tuple");
4504 default:
4505 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004506 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 }
4508 break;
4509 case Name_kind:
4510 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4511 /* child nodes of List and Tuple will have expr_context set */
4512 case List_kind:
4513 return compiler_list(c, e);
4514 case Tuple_kind:
4515 return compiler_tuple(c, e);
4516 }
4517 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004518}
4519
4520static int
4521compiler_augassign(struct compiler *c, stmt_ty s)
4522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 expr_ty e = s->v.AugAssign.target;
4524 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 switch (e->kind) {
4529 case Attribute_kind:
4530 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4531 AugLoad, e->lineno, e->col_offset, c->c_arena);
4532 if (auge == NULL)
4533 return 0;
4534 VISIT(c, expr, auge);
4535 VISIT(c, expr, s->v.AugAssign.value);
4536 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4537 auge->v.Attribute.ctx = AugStore;
4538 VISIT(c, expr, auge);
4539 break;
4540 case Subscript_kind:
4541 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4542 AugLoad, e->lineno, e->col_offset, c->c_arena);
4543 if (auge == NULL)
4544 return 0;
4545 VISIT(c, expr, auge);
4546 VISIT(c, expr, s->v.AugAssign.value);
4547 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4548 auge->v.Subscript.ctx = AugStore;
4549 VISIT(c, expr, auge);
4550 break;
4551 case Name_kind:
4552 if (!compiler_nameop(c, e->v.Name.id, Load))
4553 return 0;
4554 VISIT(c, expr, s->v.AugAssign.value);
4555 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4556 return compiler_nameop(c, e->v.Name.id, Store);
4557 default:
4558 PyErr_Format(PyExc_SystemError,
4559 "invalid node type (%d) for augmented assignment",
4560 e->kind);
4561 return 0;
4562 }
4563 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004564}
4565
4566static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004567check_ann_expr(struct compiler *c, expr_ty e)
4568{
4569 VISIT(c, expr, e);
4570 ADDOP(c, POP_TOP);
4571 return 1;
4572}
4573
4574static int
4575check_annotation(struct compiler *c, stmt_ty s)
4576{
4577 /* Annotations are only evaluated in a module or class. */
4578 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4579 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4580 return check_ann_expr(c, s->v.AnnAssign.annotation);
4581 }
4582 return 1;
4583}
4584
4585static int
4586check_ann_slice(struct compiler *c, slice_ty sl)
4587{
4588 switch(sl->kind) {
4589 case Index_kind:
4590 return check_ann_expr(c, sl->v.Index.value);
4591 case Slice_kind:
4592 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4593 return 0;
4594 }
4595 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4596 return 0;
4597 }
4598 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4599 return 0;
4600 }
4601 break;
4602 default:
4603 PyErr_SetString(PyExc_SystemError,
4604 "unexpected slice kind");
4605 return 0;
4606 }
4607 return 1;
4608}
4609
4610static int
4611check_ann_subscr(struct compiler *c, slice_ty sl)
4612{
4613 /* We check that everything in a subscript is defined at runtime. */
4614 Py_ssize_t i, n;
4615
4616 switch (sl->kind) {
4617 case Index_kind:
4618 case Slice_kind:
4619 if (!check_ann_slice(c, sl)) {
4620 return 0;
4621 }
4622 break;
4623 case ExtSlice_kind:
4624 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4625 for (i = 0; i < n; i++) {
4626 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4627 switch (subsl->kind) {
4628 case Index_kind:
4629 case Slice_kind:
4630 if (!check_ann_slice(c, subsl)) {
4631 return 0;
4632 }
4633 break;
4634 case ExtSlice_kind:
4635 default:
4636 PyErr_SetString(PyExc_SystemError,
4637 "extended slice invalid in nested slice");
4638 return 0;
4639 }
4640 }
4641 break;
4642 default:
4643 PyErr_Format(PyExc_SystemError,
4644 "invalid subscript kind %d", sl->kind);
4645 return 0;
4646 }
4647 return 1;
4648}
4649
4650static int
4651compiler_annassign(struct compiler *c, stmt_ty s)
4652{
4653 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004654 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004655
4656 assert(s->kind == AnnAssign_kind);
4657
4658 /* We perform the actual assignment first. */
4659 if (s->v.AnnAssign.value) {
4660 VISIT(c, expr, s->v.AnnAssign.value);
4661 VISIT(c, expr, targ);
4662 }
4663 switch (targ->kind) {
4664 case Name_kind:
4665 /* If we have a simple name in a module or class, store annotation. */
4666 if (s->v.AnnAssign.simple &&
4667 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4668 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004669 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4670 if (!mangled) {
4671 return 0;
4672 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004673 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004674 /* ADDOP_N decrefs its argument */
4675 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004676 }
4677 break;
4678 case Attribute_kind:
4679 if (!s->v.AnnAssign.value &&
4680 !check_ann_expr(c, targ->v.Attribute.value)) {
4681 return 0;
4682 }
4683 break;
4684 case Subscript_kind:
4685 if (!s->v.AnnAssign.value &&
4686 (!check_ann_expr(c, targ->v.Subscript.value) ||
4687 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4688 return 0;
4689 }
4690 break;
4691 default:
4692 PyErr_Format(PyExc_SystemError,
4693 "invalid node type (%d) for annotated assignment",
4694 targ->kind);
4695 return 0;
4696 }
4697 /* Annotation is evaluated last. */
4698 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4699 return 0;
4700 }
4701 return 1;
4702}
4703
4704static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004705compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 struct fblockinfo *f;
4708 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004709 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 "too many statically nested blocks");
4711 return 0;
4712 }
4713 f = &c->u->u_fblock[c->u->u_nfblocks++];
4714 f->fb_type = t;
4715 f->fb_block = b;
4716 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004717}
4718
4719static void
4720compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 struct compiler_unit *u = c->u;
4723 assert(u->u_nfblocks > 0);
4724 u->u_nfblocks--;
4725 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4726 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004727}
4728
Thomas Wouters89f507f2006-12-13 04:49:30 +00004729static int
4730compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 int i;
4732 struct compiler_unit *u = c->u;
4733 for (i = 0; i < u->u_nfblocks; ++i) {
4734 if (u->u_fblock[i].fb_type == LOOP)
4735 return 1;
4736 }
4737 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004738}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004739/* Raises a SyntaxError and returns 0.
4740 If something goes wrong, a different exception may be raised.
4741*/
4742
4743static int
4744compiler_error(struct compiler *c, const char *errstr)
4745{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004746 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748
Victor Stinner14e461d2013-08-26 22:28:21 +02004749 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 if (!loc) {
4751 Py_INCREF(Py_None);
4752 loc = Py_None;
4753 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004754 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004755 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 if (!u)
4757 goto exit;
4758 v = Py_BuildValue("(zO)", errstr, u);
4759 if (!v)
4760 goto exit;
4761 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004762 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 Py_DECREF(loc);
4764 Py_XDECREF(u);
4765 Py_XDECREF(v);
4766 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004767}
4768
4769static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770compiler_handle_subscr(struct compiler *c, const char *kind,
4771 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 /* XXX this code is duplicated */
4776 switch (ctx) {
4777 case AugLoad: /* fall through to Load */
4778 case Load: op = BINARY_SUBSCR; break;
4779 case AugStore:/* fall through to Store */
4780 case Store: op = STORE_SUBSCR; break;
4781 case Del: op = DELETE_SUBSCR; break;
4782 case Param:
4783 PyErr_Format(PyExc_SystemError,
4784 "invalid %s kind %d in subscript\n",
4785 kind, ctx);
4786 return 0;
4787 }
4788 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004789 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 }
4791 else if (ctx == AugStore) {
4792 ADDOP(c, ROT_THREE);
4793 }
4794 ADDOP(c, op);
4795 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004796}
4797
4798static int
4799compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 int n = 2;
4802 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 /* only handles the cases where BUILD_SLICE is emitted */
4805 if (s->v.Slice.lower) {
4806 VISIT(c, expr, s->v.Slice.lower);
4807 }
4808 else {
4809 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4810 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 if (s->v.Slice.upper) {
4813 VISIT(c, expr, s->v.Slice.upper);
4814 }
4815 else {
4816 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4817 }
4818
4819 if (s->v.Slice.step) {
4820 n++;
4821 VISIT(c, expr, s->v.Slice.step);
4822 }
4823 ADDOP_I(c, BUILD_SLICE, n);
4824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004825}
4826
4827static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4829 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 switch (s->kind) {
4832 case Slice_kind:
4833 return compiler_slice(c, s, ctx);
4834 case Index_kind:
4835 VISIT(c, expr, s->v.Index.value);
4836 break;
4837 case ExtSlice_kind:
4838 default:
4839 PyErr_SetString(PyExc_SystemError,
4840 "extended slice invalid in nested slice");
4841 return 0;
4842 }
4843 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004844}
4845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004846static int
4847compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4848{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004849 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 switch (s->kind) {
4851 case Index_kind:
4852 kindname = "index";
4853 if (ctx != AugStore) {
4854 VISIT(c, expr, s->v.Index.value);
4855 }
4856 break;
4857 case Slice_kind:
4858 kindname = "slice";
4859 if (ctx != AugStore) {
4860 if (!compiler_slice(c, s, ctx))
4861 return 0;
4862 }
4863 break;
4864 case ExtSlice_kind:
4865 kindname = "extended slice";
4866 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004867 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 for (i = 0; i < n; i++) {
4869 slice_ty sub = (slice_ty)asdl_seq_GET(
4870 s->v.ExtSlice.dims, i);
4871 if (!compiler_visit_nested_slice(c, sub, ctx))
4872 return 0;
4873 }
4874 ADDOP_I(c, BUILD_TUPLE, n);
4875 }
4876 break;
4877 default:
4878 PyErr_Format(PyExc_SystemError,
4879 "invalid subscript kind %d", s->kind);
4880 return 0;
4881 }
4882 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004883}
4884
Thomas Wouters89f507f2006-12-13 04:49:30 +00004885/* End of the compiler section, beginning of the assembler section */
4886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004887/* do depth-first search of basic block graph, starting with block.
4888 post records the block indices in post-order.
4889
4890 XXX must handle implicit jumps from one block to next
4891*/
4892
Thomas Wouters89f507f2006-12-13 04:49:30 +00004893struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 PyObject *a_bytecode; /* string containing bytecode */
4895 int a_offset; /* offset into bytecode */
4896 int a_nblocks; /* number of reachable blocks */
4897 basicblock **a_postorder; /* list of blocks in dfs postorder */
4898 PyObject *a_lnotab; /* string containing lnotab */
4899 int a_lnotab_off; /* offset into lnotab */
4900 int a_lineno; /* last lineno of emitted instruction */
4901 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004902};
4903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004904static void
4905dfs(struct compiler *c, basicblock *b, struct assembler *a)
4906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 int i;
4908 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 if (b->b_seen)
4911 return;
4912 b->b_seen = 1;
4913 if (b->b_next != NULL)
4914 dfs(c, b->b_next, a);
4915 for (i = 0; i < b->b_iused; i++) {
4916 instr = &b->b_instr[i];
4917 if (instr->i_jrel || instr->i_jabs)
4918 dfs(c, instr->i_target, a);
4919 }
4920 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004921}
4922
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004923static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004924stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4925{
Larry Hastings3a907972013-11-23 14:49:22 -08004926 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 struct instr *instr;
4928 if (b->b_seen || b->b_startdepth >= depth)
4929 return maxdepth;
4930 b->b_seen = 1;
4931 b->b_startdepth = depth;
4932 for (i = 0; i < b->b_iused; i++) {
4933 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004934 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4935 if (effect == PY_INVALID_STACK_EFFECT) {
4936 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4937 Py_FatalError("PyCompile_OpcodeStackEffect()");
4938 }
4939 depth += effect;
4940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 if (depth > maxdepth)
4942 maxdepth = depth;
4943 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4944 if (instr->i_jrel || instr->i_jabs) {
4945 target_depth = depth;
4946 if (instr->i_opcode == FOR_ITER) {
4947 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004948 }
4949 else if (instr->i_opcode == SETUP_FINALLY ||
4950 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 target_depth = depth+3;
4952 if (target_depth > maxdepth)
4953 maxdepth = target_depth;
4954 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004955 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4956 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4957 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 maxdepth = stackdepth_walk(c, instr->i_target,
4959 target_depth, maxdepth);
4960 if (instr->i_opcode == JUMP_ABSOLUTE ||
4961 instr->i_opcode == JUMP_FORWARD) {
4962 goto out; /* remaining code is dead */
4963 }
4964 }
4965 }
4966 if (b->b_next)
4967 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004968out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 b->b_seen = 0;
4970 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004971}
4972
4973/* Find the flow path that needs the largest stack. We assume that
4974 * cycles in the flow graph have no net effect on the stack depth.
4975 */
4976static int
4977stackdepth(struct compiler *c)
4978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 basicblock *b, *entryblock;
4980 entryblock = NULL;
4981 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4982 b->b_seen = 0;
4983 b->b_startdepth = INT_MIN;
4984 entryblock = b;
4985 }
4986 if (!entryblock)
4987 return 0;
4988 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004989}
4990
4991static int
4992assemble_init(struct assembler *a, int nblocks, int firstlineno)
4993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 memset(a, 0, sizeof(struct assembler));
4995 a->a_lineno = firstlineno;
4996 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4997 if (!a->a_bytecode)
4998 return 0;
4999 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5000 if (!a->a_lnotab)
5001 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005002 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 PyErr_NoMemory();
5004 return 0;
5005 }
5006 a->a_postorder = (basicblock **)PyObject_Malloc(
5007 sizeof(basicblock *) * nblocks);
5008 if (!a->a_postorder) {
5009 PyErr_NoMemory();
5010 return 0;
5011 }
5012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005013}
5014
5015static void
5016assemble_free(struct assembler *a)
5017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 Py_XDECREF(a->a_bytecode);
5019 Py_XDECREF(a->a_lnotab);
5020 if (a->a_postorder)
5021 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005022}
5023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005024static int
5025blocksize(basicblock *b)
5026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 int i;
5028 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005031 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005033}
5034
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005035/* Appends a pair to the end of the line number table, a_lnotab, representing
5036 the instruction's bytecode offset and line number. See
5037 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005038
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005039static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005040assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005043 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005045
Serhiy Storchakaab874002016-09-11 13:48:15 +03005046 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 if(d_bytecode == 0 && d_lineno == 0)
5052 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 if (d_bytecode > 255) {
5055 int j, nbytes, ncodes = d_bytecode / 255;
5056 nbytes = a->a_lnotab_off + 2 * ncodes;
5057 len = PyBytes_GET_SIZE(a->a_lnotab);
5058 if (nbytes >= len) {
5059 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5060 len = nbytes;
5061 else if (len <= INT_MAX / 2)
5062 len *= 2;
5063 else {
5064 PyErr_NoMemory();
5065 return 0;
5066 }
5067 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5068 return 0;
5069 }
5070 lnotab = (unsigned char *)
5071 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5072 for (j = 0; j < ncodes; j++) {
5073 *lnotab++ = 255;
5074 *lnotab++ = 0;
5075 }
5076 d_bytecode -= ncodes * 255;
5077 a->a_lnotab_off += ncodes * 2;
5078 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005079 assert(0 <= d_bytecode && d_bytecode <= 255);
5080
5081 if (d_lineno < -128 || 127 < d_lineno) {
5082 int j, nbytes, ncodes, k;
5083 if (d_lineno < 0) {
5084 k = -128;
5085 /* use division on positive numbers */
5086 ncodes = (-d_lineno) / 128;
5087 }
5088 else {
5089 k = 127;
5090 ncodes = d_lineno / 127;
5091 }
5092 d_lineno -= ncodes * k;
5093 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 nbytes = a->a_lnotab_off + 2 * ncodes;
5095 len = PyBytes_GET_SIZE(a->a_lnotab);
5096 if (nbytes >= len) {
5097 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5098 len = nbytes;
5099 else if (len <= INT_MAX / 2)
5100 len *= 2;
5101 else {
5102 PyErr_NoMemory();
5103 return 0;
5104 }
5105 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5106 return 0;
5107 }
5108 lnotab = (unsigned char *)
5109 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5110 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005111 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 d_bytecode = 0;
5113 for (j = 1; j < ncodes; j++) {
5114 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005115 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 a->a_lnotab_off += ncodes * 2;
5118 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005119 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 len = PyBytes_GET_SIZE(a->a_lnotab);
5122 if (a->a_lnotab_off + 2 >= len) {
5123 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5124 return 0;
5125 }
5126 lnotab = (unsigned char *)
5127 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 a->a_lnotab_off += 2;
5130 if (d_bytecode) {
5131 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005132 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 }
5134 else { /* First line of a block; def stmt, etc. */
5135 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005136 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 }
5138 a->a_lineno = i->i_lineno;
5139 a->a_lineno_off = a->a_offset;
5140 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005141}
5142
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005143/* assemble_emit()
5144 Extend the bytecode with a new instruction.
5145 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005146*/
5147
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005148static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005149assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005150{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005151 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005153 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005154
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005155 arg = i->i_oparg;
5156 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 if (i->i_lineno && !assemble_lnotab(a, i))
5158 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005159 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 if (len > PY_SSIZE_T_MAX / 2)
5161 return 0;
5162 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5163 return 0;
5164 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005165 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005167 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005169}
5170
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005171static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005172assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005175 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 /* Compute the size of each block and fixup jump args.
5179 Replace block pointer with position in bytecode. */
5180 do {
5181 totsize = 0;
5182 for (i = a->a_nblocks - 1; i >= 0; i--) {
5183 b = a->a_postorder[i];
5184 bsize = blocksize(b);
5185 b->b_offset = totsize;
5186 totsize += bsize;
5187 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005188 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5190 bsize = b->b_offset;
5191 for (i = 0; i < b->b_iused; i++) {
5192 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005193 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 /* Relative jumps are computed relative to
5195 the instruction pointer after fetching
5196 the jump instruction.
5197 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005198 bsize += isize;
5199 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005201 if (instr->i_jrel) {
5202 instr->i_oparg -= bsize;
5203 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005204 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005205 if (instrsize(instr->i_oparg) != isize) {
5206 extended_arg_recompile = 1;
5207 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 }
5210 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 /* XXX: This is an awful hack that could hurt performance, but
5213 on the bright side it should work until we come up
5214 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 The issue is that in the first loop blocksize() is called
5217 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005218 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 So we loop until we stop seeing new EXTENDED_ARGs.
5222 The only EXTENDED_ARGs that could be popping up are
5223 ones in jump instructions. So this should converge
5224 fairly quickly.
5225 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005226 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005227}
5228
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005229static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005230dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005233 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 tuple = PyTuple_New(size);
5236 if (tuple == NULL)
5237 return NULL;
5238 while (PyDict_Next(dict, &pos, &k, &v)) {
5239 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005240 /* The keys of the dictionary are tuples. (see compiler_add_o
5241 * and _PyCode_ConstantKey). The object we want is always second,
5242 * though. */
5243 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 Py_INCREF(k);
5245 assert((i - offset) < size);
5246 assert((i - offset) >= 0);
5247 PyTuple_SET_ITEM(tuple, i - offset, k);
5248 }
5249 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005250}
5251
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005252static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005253compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005256 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005258 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 if (ste->ste_nested)
5260 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005261 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005263 if (!ste->ste_generator && ste->ste_coroutine)
5264 flags |= CO_COROUTINE;
5265 if (ste->ste_generator && ste->ste_coroutine)
5266 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 if (ste->ste_varargs)
5268 flags |= CO_VARARGS;
5269 if (ste->ste_varkeywords)
5270 flags |= CO_VARKEYWORDS;
5271 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 /* (Only) inherit compilerflags in PyCF_MASK */
5274 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005275
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005276 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5277 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5278 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005282}
5283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005284static PyCodeObject *
5285makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 PyObject *tmp;
5288 PyCodeObject *co = NULL;
5289 PyObject *consts = NULL;
5290 PyObject *names = NULL;
5291 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 PyObject *name = NULL;
5293 PyObject *freevars = NULL;
5294 PyObject *cellvars = NULL;
5295 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005296 Py_ssize_t nlocals;
5297 int nlocals_int;
5298 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005299 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 tmp = dict_keys_inorder(c->u->u_consts, 0);
5302 if (!tmp)
5303 goto error;
5304 consts = PySequence_List(tmp); /* optimize_code requires a list */
5305 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 names = dict_keys_inorder(c->u->u_names, 0);
5308 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5309 if (!consts || !names || !varnames)
5310 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5313 if (!cellvars)
5314 goto error;
5315 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5316 if (!freevars)
5317 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005318
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005319 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005320 assert(nlocals < INT_MAX);
5321 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 flags = compute_code_flags(c);
5324 if (flags < 0)
5325 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5328 if (!bytecode)
5329 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5332 if (!tmp)
5333 goto error;
5334 Py_DECREF(consts);
5335 consts = tmp;
5336
Victor Stinnerf8e32212013-11-19 23:56:34 +01005337 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5338 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5339 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005340 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 bytecode, consts, names, varnames,
5342 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005343 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 c->u->u_firstlineno,
5345 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 Py_XDECREF(consts);
5348 Py_XDECREF(names);
5349 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 Py_XDECREF(name);
5351 Py_XDECREF(freevars);
5352 Py_XDECREF(cellvars);
5353 Py_XDECREF(bytecode);
5354 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005355}
5356
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005357
5358/* For debugging purposes only */
5359#if 0
5360static void
5361dump_instr(const struct instr *i)
5362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 const char *jrel = i->i_jrel ? "jrel " : "";
5364 const char *jabs = i->i_jabs ? "jabs " : "";
5365 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005368 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005370 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5372 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005373}
5374
5375static void
5376dump_basicblock(const basicblock *b)
5377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 const char *seen = b->b_seen ? "seen " : "";
5379 const char *b_return = b->b_return ? "return " : "";
5380 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5381 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5382 if (b->b_instr) {
5383 int i;
5384 for (i = 0; i < b->b_iused; i++) {
5385 fprintf(stderr, " [%02d] ", i);
5386 dump_instr(b->b_instr + i);
5387 }
5388 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005389}
5390#endif
5391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005392static PyCodeObject *
5393assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 basicblock *b, *entryblock;
5396 struct assembler a;
5397 int i, j, nblocks;
5398 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 /* Make sure every block that falls off the end returns None.
5401 XXX NEXT_BLOCK() isn't quite right, because if the last
5402 block ends with a jump or return b_next shouldn't set.
5403 */
5404 if (!c->u->u_curblock->b_return) {
5405 NEXT_BLOCK(c);
5406 if (addNone)
5407 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5408 ADDOP(c, RETURN_VALUE);
5409 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 nblocks = 0;
5412 entryblock = NULL;
5413 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5414 nblocks++;
5415 entryblock = b;
5416 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 /* Set firstlineno if it wasn't explicitly set. */
5419 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005420 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5422 else
5423 c->u->u_firstlineno = 1;
5424 }
5425 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5426 goto error;
5427 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 /* Can't modify the bytecode after computing jump offsets. */
5430 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 /* Emit code in reverse postorder from dfs. */
5433 for (i = a.a_nblocks - 1; i >= 0; i--) {
5434 b = a.a_postorder[i];
5435 for (j = 0; j < b->b_iused; j++)
5436 if (!assemble_emit(&a, &b->b_instr[j]))
5437 goto error;
5438 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5441 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005442 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 assemble_free(&a);
5448 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005449}
Georg Brandl8334fd92010-12-04 10:26:46 +00005450
5451#undef PyAST_Compile
5452PyAPI_FUNC(PyCodeObject *)
5453PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5454 PyArena *arena)
5455{
5456 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5457}