blob: e547c2fd591c498073a7ad3f6ff8d947d17527cd [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (c.c_st == NULL) {
336 if (!PyErr_Occurred())
337 PyErr_SetString(PyExc_SystemError, "no symtable");
338 goto finally;
339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Thomas Wouters1175c432006-02-27 22:49:54 +0000343 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 compiler_free(&c);
345 assert(co || PyErr_Occurred());
346 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347}
348
349PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200350PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
351 int optimize, PyArena *arena)
352{
353 PyObject *filename;
354 PyCodeObject *co;
355 filename = PyUnicode_DecodeFSDefault(filename_str);
356 if (filename == NULL)
357 return NULL;
358 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
359 Py_DECREF(filename);
360 return co;
361
362}
363
364PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365PyNode_Compile(struct _node *n, const char *filename)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyCodeObject *co = NULL;
368 mod_ty mod;
369 PyArena *arena = PyArena_New();
370 if (!arena)
371 return NULL;
372 mod = PyAST_FromNode(n, NULL, filename, arena);
373 if (mod)
374 co = PyAST_Compile(mod, filename, NULL, arena);
375 PyArena_Free(arena);
376 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000377}
378
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (c->c_st)
383 PySymtable_Free(c->c_st);
384 if (c->c_future)
385 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000388}
389
Guido van Rossum79f25d91997-04-29 20:08:16 +0000390static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t i, n;
394 PyObject *v, *k;
395 PyObject *dict = PyDict_New();
396 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 n = PyList_Size(list);
399 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100400 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (!v) {
402 Py_DECREF(dict);
403 return NULL;
404 }
405 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100406 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
408 Py_XDECREF(k);
409 Py_DECREF(v);
410 Py_DECREF(dict);
411 return NULL;
412 }
413 Py_DECREF(k);
414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100462 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100469 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
474 Py_XDECREF(tuple);
475 return NULL;
476 }
477 Py_DECREF(item);
478 Py_DECREF(tuple);
479 }
480 }
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000483}
484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485static void
486compiler_unit_check(struct compiler_unit *u)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 basicblock *block;
489 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700490 assert((uintptr_t)block != 0xcbcbcbcbU);
491 assert((uintptr_t)block != 0xfbfbfbfbU);
492 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (block->b_instr != NULL) {
494 assert(block->b_ialloc > 0);
495 assert(block->b_iused > 0);
496 assert(block->b_ialloc >= block->b_iused);
497 }
498 else {
499 assert (block->b_iused == 0);
500 assert (block->b_ialloc == 0);
501 }
502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503}
504
505static void
506compiler_unit_free(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 compiler_unit_check(u);
511 b = u->u_blocks;
512 while (b != NULL) {
513 if (b->b_instr)
514 PyObject_Free((void *)b->b_instr);
515 next = b->b_list;
516 PyObject_Free((void *)b);
517 b = next;
518 }
519 Py_CLEAR(u->u_ste);
520 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400521 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_CLEAR(u->u_consts);
523 Py_CLEAR(u->u_names);
524 Py_CLEAR(u->u_varnames);
525 Py_CLEAR(u->u_freevars);
526 Py_CLEAR(u->u_cellvars);
527 Py_CLEAR(u->u_private);
528 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100532compiler_enter_scope(struct compiler *c, identifier name,
533 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100536 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
539 struct compiler_unit));
540 if (!u) {
541 PyErr_NoMemory();
542 return 0;
543 }
544 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100545 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_argcount = 0;
547 u->u_kwonlyargcount = 0;
548 u->u_ste = PySymtable_Lookup(c->c_st, key);
549 if (!u->u_ste) {
550 compiler_unit_free(u);
551 return 0;
552 }
553 Py_INCREF(name);
554 u->u_name = name;
555 u->u_varnames = list2dict(u->u_ste->ste_varnames);
556 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
557 if (!u->u_varnames || !u->u_cellvars) {
558 compiler_unit_free(u);
559 return 0;
560 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000562 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300564 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 int res;
566 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200567 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 name = _PyUnicode_FromId(&PyId___class__);
569 if (!name) {
570 compiler_unit_free(u);
571 return 0;
572 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100573 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 if (!tuple) {
575 compiler_unit_free(u);
576 return 0;
577 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300578 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (res < 0) {
581 compiler_unit_free(u);
582 return 0;
583 }
584 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200587 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (!u->u_freevars) {
589 compiler_unit_free(u);
590 return 0;
591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_blocks = NULL;
594 u->u_nfblocks = 0;
595 u->u_firstlineno = lineno;
596 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000597 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 u->u_lineno_set = 0;
599 u->u_consts = PyDict_New();
600 if (!u->u_consts) {
601 compiler_unit_free(u);
602 return 0;
603 }
604 u->u_names = PyDict_New();
605 if (!u->u_names) {
606 compiler_unit_free(u);
607 return 0;
608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Push the old compiler_unit on the stack. */
613 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400614 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
616 Py_XDECREF(capsule);
617 compiler_unit_free(u);
618 return 0;
619 }
620 Py_DECREF(capsule);
621 u->u_private = c->u->u_private;
622 Py_XINCREF(u->u_private);
623 }
624 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627
628 block = compiler_new_block(c);
629 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400633 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
634 if (!compiler_set_qualname(c))
635 return 0;
636 }
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642compiler_exit_scope(struct compiler *c)
643{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100644 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel--;
648 compiler_unit_free(c->u);
649 /* Restore c->u to the parent unit. */
650 n = PyList_GET_SIZE(c->c_stack) - 1;
651 if (n >= 0) {
652 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400653 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(c->u);
655 /* we are deleting from a list so this really shouldn't fail */
656 if (PySequence_DelItem(c->c_stack, n) < 0)
657 Py_FatalError("compiler_exit_scope()");
658 compiler_unit_check(c->u);
659 }
660 else
661 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663}
664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665static int
666compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 _Py_static_string(dot_locals, ".<locals>");
670 Py_ssize_t stack_size;
671 struct compiler_unit *u = c->u;
672 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400676 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 if (stack_size > 1) {
678 int scope, force_global = 0;
679 struct compiler_unit *parent;
680 PyObject *mangled, *capsule;
681
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400682 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 assert(parent);
685
Yury Selivanov75445082015-05-11 22:57:16 -0400686 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
687 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 assert(u->u_name);
690 mangled = _Py_Mangle(parent->u_private, u->u_name);
691 if (!mangled)
692 return 0;
693 scope = PyST_GetScope(parent->u_ste, mangled);
694 Py_DECREF(mangled);
695 assert(scope != GLOBAL_IMPLICIT);
696 if (scope == GLOBAL_EXPLICIT)
697 force_global = 1;
698 }
699
700 if (!force_global) {
701 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400702 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
704 dot_locals_str = _PyUnicode_FromId(&dot_locals);
705 if (dot_locals_str == NULL)
706 return 0;
707 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
708 if (base == NULL)
709 return 0;
710 }
711 else {
712 Py_INCREF(parent->u_qualname);
713 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100715 }
716 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400717
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 if (base != NULL) {
719 dot_str = _PyUnicode_FromId(&dot);
720 if (dot_str == NULL) {
721 Py_DECREF(base);
722 return 0;
723 }
724 name = PyUnicode_Concat(base, dot_str);
725 Py_DECREF(base);
726 if (name == NULL)
727 return 0;
728 PyUnicode_Append(&name, u->u_name);
729 if (name == NULL)
730 return 0;
731 }
732 else {
733 Py_INCREF(u->u_name);
734 name = u->u_name;
735 }
736 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739}
740
Eric V. Smith235a6f02015-09-19 14:51:32 -0400741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742/* Allocate a new block and return a pointer to it.
743 Returns NULL on error.
744*/
745
746static basicblock *
747compiler_new_block(struct compiler *c)
748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 basicblock *b;
750 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 u = c->u;
753 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
754 if (b == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 memset((void *)b, 0, sizeof(basicblock));
759 /* Extend the singly linked list of blocks with new block. */
760 b->b_list = u->u_blocks;
761 u->u_blocks = b;
762 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700811 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
Larry Hastings3a907972013-11-23 14:49:22 -0800856int
857PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400884 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_MODULO:
886 case BINARY_ADD:
887 case BINARY_SUBTRACT:
888 case BINARY_SUBSCR:
889 case BINARY_FLOOR_DIVIDE:
890 case BINARY_TRUE_DIVIDE:
891 return -1;
892 case INPLACE_FLOOR_DIVIDE:
893 case INPLACE_TRUE_DIVIDE:
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_ADD:
897 case INPLACE_SUBTRACT:
898 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400899 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_MODULO:
901 return -1;
902 case STORE_SUBSCR:
903 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400932 case WITH_CLEANUP_START:
933 return 1;
934 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case RETURN_VALUE:
937 return -1;
938 case IMPORT_STAR:
939 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700940 case SETUP_ANNOTATIONS:
941 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300979 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300983 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400984 case BUILD_SET_UNPACK:
985 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400986 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700987 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300990 case BUILD_CONST_KEY_MAP:
991 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case LOAD_ATTR:
993 return 0;
994 case COMPARE_OP:
995 return -1;
996 case IMPORT_NAME:
997 return -1;
998 case IMPORT_FROM:
999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case JUMP_FORWARD:
1002 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1003 case JUMP_IF_FALSE_OR_POP: /* "" */
1004 case JUMP_ABSOLUTE:
1005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case POP_JUMP_IF_FALSE:
1008 case POP_JUMP_IF_TRUE:
1009 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_GLOBAL:
1012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case CONTINUE_LOOP:
1015 return 0;
1016 case SETUP_LOOP:
1017 return 0;
1018 case SETUP_EXCEPT:
1019 case SETUP_FINALLY:
1020 return 6; /* can push 3 values for the new exception
1021 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case LOAD_FAST:
1024 return 1;
1025 case STORE_FAST:
1026 return -1;
1027 case DELETE_FAST:
1028 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001029 case STORE_ANNOTATION:
1030 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case RAISE_VARARGS:
1033 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001035 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001036 case CALL_METHOD:
1037 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg-1;
1040 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001041 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001042 case MAKE_FUNCTION:
1043 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1044 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case BUILD_SLICE:
1046 if (oparg == 3)
1047 return -2;
1048 else
1049 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case LOAD_CLOSURE:
1052 return 1;
1053 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001054 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 1;
1056 case STORE_DEREF:
1057 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001058 case DELETE_DEREF:
1059 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001060 case GET_AWAITABLE:
1061 return 0;
1062 case SETUP_ASYNC_WITH:
1063 return 6;
1064 case BEFORE_ASYNC_WITH:
1065 return 1;
1066 case GET_AITER:
1067 return 0;
1068 case GET_ANEXT:
1069 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001070 case GET_YIELD_FROM_ITER:
1071 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001072 case FORMAT_VALUE:
1073 /* If there's a fmt_spec on the stack, we go from 2->1,
1074 else 1->1. */
1075 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001076 case LOAD_METHOD:
1077 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001079 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Larry Hastings3a907972013-11-23 14:49:22 -08001081 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082}
1083
1084/* Add an opcode with no argument.
1085 Returns 0 on failure, 1 on success.
1086*/
1087
1088static int
1089compiler_addop(struct compiler *c, int opcode)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 basicblock *b;
1092 struct instr *i;
1093 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001094 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 off = compiler_next_instr(c, c->u->u_curblock);
1096 if (off < 0)
1097 return 0;
1098 b = c->u->u_curblock;
1099 i = &b->b_instr[off];
1100 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (opcode == RETURN_VALUE)
1103 b->b_return = 1;
1104 compiler_set_lineno(c, off);
1105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106}
1107
Victor Stinnerf8e32212013-11-19 23:56:34 +01001108static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *t, *v;
1112 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Victor Stinnerefb24132016-01-22 12:33:12 +01001114 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (t == NULL)
1116 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 v = PyDict_GetItem(dict, t);
1119 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001120 if (PyErr_Occurred()) {
1121 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001123 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001124 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001125 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!v) {
1127 Py_DECREF(t);
1128 return -1;
1129 }
1130 if (PyDict_SetItem(dict, t, v) < 0) {
1131 Py_DECREF(t);
1132 Py_DECREF(v);
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 }
1137 else
1138 arg = PyLong_AsLong(v);
1139 Py_DECREF(t);
1140 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
1143static int
1144compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001149 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return compiler_addop_i(c, opcode, arg);
1151}
1152
1153static int
1154compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001157 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1159 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 arg = compiler_add_o(c, dict, mangled);
1162 Py_DECREF(mangled);
1163 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return compiler_addop_i(c, opcode, arg);
1166}
1167
1168/* Add an opcode with an integer argument.
1169 Returns 0 on failure, 1 on success.
1170*/
1171
1172static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 struct instr *i;
1176 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Victor Stinner2ad474b2016-03-01 23:34:47 +01001178 /* oparg value is unsigned, but a signed C int is usually used to store
1179 it in the C code (like Python/ceval.c).
1180
1181 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1182
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 The argument of a concrete bytecode instruction is limited to 8-bit.
1184 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1185 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001186 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 off = compiler_next_instr(c, c->u->u_curblock);
1189 if (off < 0)
1190 return 0;
1191 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001192 i->i_opcode = opcode;
1193 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001204 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 assert(b != NULL);
1206 off = compiler_next_instr(c, c->u->u_curblock);
1207 if (off < 0)
1208 return 0;
1209 i = &c->u->u_curblock->b_instr[off];
1210 i->i_opcode = opcode;
1211 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001220/* NEXT_BLOCK() creates an implicit jump from the current block
1221 to the new block.
1222
1223 The returns inside this macro make it impossible to decref objects
1224 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (compiler_next_block((C)) == NULL) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop((C), (OP))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001236#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop((C), (OP))) { \
1238 compiler_exit_scope(c); \
1239 return 0; \
1240 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001241}
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001248/* Same as ADDOP_O, but steals a reference. */
1249#define ADDOP_N(C, OP, O, TYPE) { \
1250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1251 Py_DECREF((O)); \
1252 return 0; \
1253 } \
1254 Py_DECREF((O)); \
1255}
1256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_i((C), (OP), (O))) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop_j((C), (OP), (O), 1)) \
1269 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
1272#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_addop_j((C), (OP), (O), 0)) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
1277/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1278 the ASDL name to synthesize the name of the C type and the visit function.
1279*/
1280
1281#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_visit_ ## TYPE((C), (V))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_visit_ ## TYPE((C), (V))) { \
1288 compiler_exit_scope(c); \
1289 return 0; \
1290 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001291}
1292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_slice((C), (V), (CTX))) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 int _i; \
1300 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1301 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1302 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1303 if (!compiler_visit_ ## TYPE((C), elt)) \
1304 return 0; \
1305 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 int _i; \
1310 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1311 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1312 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1313 if (!compiler_visit_ ## TYPE((C), elt)) { \
1314 compiler_exit_scope(c); \
1315 return 0; \
1316 } \
1317 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001318}
1319
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001321is_const(expr_ty e)
1322{
1323 switch (e->kind) {
1324 case Constant_kind:
1325 case Num_kind:
1326 case Str_kind:
1327 case Bytes_kind:
1328 case Ellipsis_kind:
1329 case NameConstant_kind:
1330 return 1;
1331 default:
1332 return 0;
1333 }
1334}
1335
1336static PyObject *
1337get_const_value(expr_ty e)
1338{
1339 switch (e->kind) {
1340 case Constant_kind:
1341 return e->v.Constant.value;
1342 case Num_kind:
1343 return e->v.Num.n;
1344 case Str_kind:
1345 return e->v.Str.s;
1346 case Bytes_kind:
1347 return e->v.Bytes.s;
1348 case Ellipsis_kind:
1349 return Py_Ellipsis;
1350 case NameConstant_kind:
1351 return e->v.NameConstant.value;
1352 default:
1353 assert(!is_const(e));
1354 return NULL;
1355 }
1356}
1357
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001358/* Search if variable annotations are present statically in a block. */
1359
1360static int
1361find_ann(asdl_seq *stmts)
1362{
1363 int i, j, res = 0;
1364 stmt_ty st;
1365
1366 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1367 st = (stmt_ty)asdl_seq_GET(stmts, i);
1368 switch (st->kind) {
1369 case AnnAssign_kind:
1370 return 1;
1371 case For_kind:
1372 res = find_ann(st->v.For.body) ||
1373 find_ann(st->v.For.orelse);
1374 break;
1375 case AsyncFor_kind:
1376 res = find_ann(st->v.AsyncFor.body) ||
1377 find_ann(st->v.AsyncFor.orelse);
1378 break;
1379 case While_kind:
1380 res = find_ann(st->v.While.body) ||
1381 find_ann(st->v.While.orelse);
1382 break;
1383 case If_kind:
1384 res = find_ann(st->v.If.body) ||
1385 find_ann(st->v.If.orelse);
1386 break;
1387 case With_kind:
1388 res = find_ann(st->v.With.body);
1389 break;
1390 case AsyncWith_kind:
1391 res = find_ann(st->v.AsyncWith.body);
1392 break;
1393 case Try_kind:
1394 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1395 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1396 st->v.Try.handlers, j);
1397 if (find_ann(handler->v.ExceptHandler.body)) {
1398 return 1;
1399 }
1400 }
1401 res = find_ann(st->v.Try.body) ||
1402 find_ann(st->v.Try.finalbody) ||
1403 find_ann(st->v.Try.orelse);
1404 break;
1405 default:
1406 res = 0;
1407 }
1408 if (res) {
1409 break;
1410 }
1411 }
1412 return res;
1413}
1414
1415/* Compile a sequence of statements, checking for a docstring
1416 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
1418static int
INADA Naokicb41b272017-02-23 00:31:59 +09001419compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001421 /* Set current line number to the line number of first statement.
1422 This way line number for SETUP_ANNOTATIONS will always
1423 coincide with the line number of first "real" statement in module.
1424 If body is empy, then lineno will be set later in assemble. */
1425 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1426 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001427 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001428 c->u->u_lineno = st->lineno;
1429 }
1430 /* Every annotated class and module should have __annotations__. */
1431 if (find_ann(stmts)) {
1432 ADDOP(c, SETUP_ANNOTATIONS);
1433 }
INADA Naokicb41b272017-02-23 00:31:59 +09001434 /* if not -OO mode, set docstring */
1435 if (c->c_optimize < 2 && docstring) {
1436 ADDOP_O(c, LOAD_CONST, docstring, consts);
1437 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
INADA Naokicb41b272017-02-23 00:31:59 +09001439 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441}
1442
1443static PyCodeObject *
1444compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyCodeObject *co;
1447 int addNone = 1;
1448 static PyObject *module;
1449 if (!module) {
1450 module = PyUnicode_InternFromString("<module>");
1451 if (!module)
1452 return NULL;
1453 }
1454 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001455 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return NULL;
1457 switch (mod->kind) {
1458 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001459 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 compiler_exit_scope(c);
1461 return 0;
1462 }
1463 break;
1464 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001465 if (find_ann(mod->v.Interactive.body)) {
1466 ADDOP(c, SETUP_ANNOTATIONS);
1467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 c->c_interactive = 1;
1469 VISIT_SEQ_IN_SCOPE(c, stmt,
1470 mod->v.Interactive.body);
1471 break;
1472 case Expression_kind:
1473 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1474 addNone = 0;
1475 break;
1476 case Suite_kind:
1477 PyErr_SetString(PyExc_SystemError,
1478 "suite should not be possible");
1479 return 0;
1480 default:
1481 PyErr_Format(PyExc_SystemError,
1482 "module kind %d should not be possible",
1483 mod->kind);
1484 return 0;
1485 }
1486 co = assemble(c, addNone);
1487 compiler_exit_scope(c);
1488 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001489}
1490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491/* The test for LOCAL must come before the test for FREE in order to
1492 handle classes where name is both local and free. The local var is
1493 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001494*/
1495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496static int
1497get_ref_type(struct compiler *c, PyObject *name)
1498{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001499 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001500 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001501 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001502 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001503 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (scope == 0) {
1505 char buf[350];
1506 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001507 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001509 PyUnicode_AsUTF8(name),
1510 PyUnicode_AsUTF8(c->u->u_name),
1511 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1512 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1513 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1514 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 );
1516 Py_FatalError(buf);
1517 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
1522static int
1523compiler_lookup_arg(PyObject *dict, PyObject *name)
1524{
1525 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001526 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001528 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001530 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001532 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001533 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001537compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001539 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001540 if (qualname == NULL)
1541 qualname = co->co_name;
1542
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001543 if (free) {
1544 for (i = 0; i < free; ++i) {
1545 /* Bypass com_addop_varname because it will generate
1546 LOAD_DEREF but LOAD_CLOSURE is needed.
1547 */
1548 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1549 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001551 /* Special case: If a class contains a method with a
1552 free variable that has the same name as a method,
1553 the name will be considered free *and* local in the
1554 class. It should be handled by the closure, as
1555 well as by the normal name loookup logic.
1556 */
1557 reftype = get_ref_type(c, name);
1558 if (reftype == CELL)
1559 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1560 else /* (reftype == FREE) */
1561 arg = compiler_lookup_arg(c->u->u_freevars, name);
1562 if (arg == -1) {
1563 fprintf(stderr,
1564 "lookup %s in %s %d %d\n"
1565 "freevars of %s: %s\n",
1566 PyUnicode_AsUTF8(PyObject_Repr(name)),
1567 PyUnicode_AsUTF8(c->u->u_name),
1568 reftype, arg,
1569 PyUnicode_AsUTF8(co->co_name),
1570 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1571 Py_FatalError("compiler_make_closure()");
1572 }
1573 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001575 flags |= 0x08;
1576 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001579 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001580 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582}
1583
1584static int
1585compiler_decorators(struct compiler *c, asdl_seq* decos)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (!decos)
1590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1593 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1594 }
1595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596}
1597
1598static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001599compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001601{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001602 /* Push a dict of keyword-only default values.
1603
1604 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1605 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001606 int i;
1607 PyObject *keys = NULL;
1608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1610 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1611 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1612 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001613 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001614 if (!mangled) {
1615 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001617 if (keys == NULL) {
1618 keys = PyList_New(1);
1619 if (keys == NULL) {
1620 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001621 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001622 }
1623 PyList_SET_ITEM(keys, 0, mangled);
1624 }
1625 else {
1626 int res = PyList_Append(keys, mangled);
1627 Py_DECREF(mangled);
1628 if (res == -1) {
1629 goto error;
1630 }
1631 }
1632 if (!compiler_visit_expr(c, default_)) {
1633 goto error;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 }
1636 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001637 if (keys != NULL) {
1638 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1639 PyObject *keys_tuple = PyList_AsTuple(keys);
1640 Py_DECREF(keys);
1641 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001642 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001643 }
1644 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1645 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001646 assert(default_count > 0);
1647 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001648 }
1649 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001650 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001651 }
1652
1653error:
1654 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001655 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001656}
1657
1658static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001659compiler_visit_argannotation(struct compiler *c, identifier id,
1660 expr_ty annotation, PyObject *names)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001663 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001665 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001666 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001667 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001668 if (PyList_Append(names, mangled) < 0) {
1669 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001670 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001671 }
1672 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001674 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001675}
1676
1677static int
1678compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1679 PyObject *names)
1680{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001681 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 for (i = 0; i < asdl_seq_LEN(args); i++) {
1683 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001684 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 c,
1686 arg->arg,
1687 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001688 names))
1689 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001692}
1693
1694static int
1695compiler_visit_annotations(struct compiler *c, arguments_ty args,
1696 expr_ty returns)
1697{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001698 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001699 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001700
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001701 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 */
1703 static identifier return_str;
1704 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001705 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 names = PyList_New(0);
1707 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001708 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001709
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001710 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001712 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001713 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001714 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001716 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001718 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001719 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001720 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (!return_str) {
1724 return_str = PyUnicode_InternFromString("return");
1725 if (!return_str)
1726 goto error;
1727 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001728 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 goto error;
1730 }
1731
1732 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001734 PyObject *keytuple = PyList_AsTuple(names);
1735 Py_DECREF(names);
1736 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001737 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001739 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1740 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001741 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001743 else {
1744 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001745 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001746 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001747
1748error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001750 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001751}
1752
1753static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001754compiler_visit_defaults(struct compiler *c, arguments_ty args)
1755{
1756 VISIT_SEQ(c, expr, args->defaults);
1757 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759}
1760
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761static Py_ssize_t
1762compiler_default_arguments(struct compiler *c, arguments_ty args)
1763{
1764 Py_ssize_t funcflags = 0;
1765 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001766 if (!compiler_visit_defaults(c, args))
1767 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 funcflags |= 0x01;
1769 }
1770 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001772 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001773 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001774 return -1;
1775 }
1776 else if (res > 0) {
1777 funcflags |= 0x02;
1778 }
1779 }
1780 return funcflags;
1781}
1782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783static int
Yury Selivanov75445082015-05-11 22:57:16 -04001784compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001787 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001788 arguments_ty args;
1789 expr_ty returns;
1790 identifier name;
1791 asdl_seq* decos;
1792 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001793 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001795 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796
Yury Selivanov75445082015-05-11 22:57:16 -04001797 if (is_async) {
1798 assert(s->kind == AsyncFunctionDef_kind);
1799
1800 args = s->v.AsyncFunctionDef.args;
1801 returns = s->v.AsyncFunctionDef.returns;
1802 decos = s->v.AsyncFunctionDef.decorator_list;
1803 name = s->v.AsyncFunctionDef.name;
1804 body = s->v.AsyncFunctionDef.body;
1805
1806 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1807 } else {
1808 assert(s->kind == FunctionDef_kind);
1809
1810 args = s->v.FunctionDef.args;
1811 returns = s->v.FunctionDef.returns;
1812 decos = s->v.FunctionDef.decorator_list;
1813 name = s->v.FunctionDef.name;
1814 body = s->v.FunctionDef.body;
1815
1816 scope_type = COMPILER_SCOPE_FUNCTION;
1817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (!compiler_decorators(c, decos))
1820 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001821
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822 funcflags = compiler_default_arguments(c, args);
1823 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001825 }
1826
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001827 annotations = compiler_visit_annotations(c, args, returns);
1828 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 return 0;
1830 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001831 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001832 funcflags |= 0x04;
1833 }
1834
1835 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1836 return 0;
1837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838
INADA Naokicb41b272017-02-23 00:31:59 +09001839 /* if not -OO mode, add docstring */
1840 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1841 docstring = s->v.FunctionDef.docstring;
1842 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 compiler_exit_scope(c);
1844 return 0;
1845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->u->u_argcount = asdl_seq_LEN(args->args);
1848 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001850 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001852 qualname = c->u->u_qualname;
1853 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001855 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001856 Py_XDECREF(qualname);
1857 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001861 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* decorators */
1866 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1867 ADDOP_I(c, CALL_FUNCTION, 1);
1868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Yury Selivanov75445082015-05-11 22:57:16 -04001870 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871}
1872
1873static int
1874compiler_class(struct compiler *c, stmt_ty s)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyCodeObject *co;
1877 PyObject *str;
1878 int i;
1879 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!compiler_decorators(c, decos))
1882 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* ultimately generate code for:
1885 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1886 where:
1887 <func> is a function/closure created from the class body;
1888 it has a single argument (__locals__) where the dict
1889 (or MutableSequence) representing the locals is passed
1890 <name> is the class name
1891 <bases> is the positional arguments and *varargs argument
1892 <keywords> is the keyword arguments and **kwds argument
1893 This borrows from compiler_call.
1894 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001897 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1898 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 return 0;
1900 /* this block represents what we do in the new scope */
1901 {
1902 /* use the class name for name mangling */
1903 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001904 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* load (global) __name__ ... */
1906 str = PyUnicode_InternFromString("__name__");
1907 if (!str || !compiler_nameop(c, str, Load)) {
1908 Py_XDECREF(str);
1909 compiler_exit_scope(c);
1910 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_DECREF(str);
1913 /* ... and store it as __module__ */
1914 str = PyUnicode_InternFromString("__module__");
1915 if (!str || !compiler_nameop(c, str, Store)) {
1916 Py_XDECREF(str);
1917 compiler_exit_scope(c);
1918 return 0;
1919 }
1920 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001921 assert(c->u->u_qualname);
1922 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 str = PyUnicode_InternFromString("__qualname__");
1924 if (!str || !compiler_nameop(c, str, Store)) {
1925 Py_XDECREF(str);
1926 compiler_exit_scope(c);
1927 return 0;
1928 }
1929 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001931 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 compiler_exit_scope(c);
1933 return 0;
1934 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001935 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001936 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001937 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001938 str = PyUnicode_InternFromString("__class__");
1939 if (str == NULL) {
1940 compiler_exit_scope(c);
1941 return 0;
1942 }
1943 i = compiler_lookup_arg(c->u->u_cellvars, str);
1944 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001945 if (i < 0) {
1946 compiler_exit_scope(c);
1947 return 0;
1948 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001949 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001952 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001953 str = PyUnicode_InternFromString("__classcell__");
1954 if (!str || !compiler_nameop(c, str, Store)) {
1955 Py_XDECREF(str);
1956 compiler_exit_scope(c);
1957 return 0;
1958 }
1959 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001961 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001962 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001963 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001964 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001965 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001966 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* create the code object */
1968 co = assemble(c, 1);
1969 }
1970 /* leave the new scope */
1971 compiler_exit_scope(c);
1972 if (co == NULL)
1973 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* 2. load the 'build_class' function */
1976 ADDOP(c, LOAD_BUILD_CLASS);
1977
1978 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001979 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Py_DECREF(co);
1981
1982 /* 4. load class name */
1983 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1984
1985 /* 5. generate the rest of the code for the call */
1986 if (!compiler_call_helper(c, 2,
1987 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001988 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 0;
1990
1991 /* 6. apply decorators */
1992 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1993 ADDOP_I(c, CALL_FUNCTION, 1);
1994 }
1995
1996 /* 7. store into <name> */
1997 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1998 return 0;
1999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000}
2001
2002static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002003cmpop(cmpop_ty op)
2004{
2005 switch (op) {
2006 case Eq:
2007 return PyCmp_EQ;
2008 case NotEq:
2009 return PyCmp_NE;
2010 case Lt:
2011 return PyCmp_LT;
2012 case LtE:
2013 return PyCmp_LE;
2014 case Gt:
2015 return PyCmp_GT;
2016 case GtE:
2017 return PyCmp_GE;
2018 case Is:
2019 return PyCmp_IS;
2020 case IsNot:
2021 return PyCmp_IS_NOT;
2022 case In:
2023 return PyCmp_IN;
2024 case NotIn:
2025 return PyCmp_NOT_IN;
2026 default:
2027 return PyCmp_BAD;
2028 }
2029}
2030
2031static int
2032compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2033{
2034 switch (e->kind) {
2035 case UnaryOp_kind:
2036 if (e->v.UnaryOp.op == Not)
2037 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2038 /* fallback to general implementation */
2039 break;
2040 case BoolOp_kind: {
2041 asdl_seq *s = e->v.BoolOp.values;
2042 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2043 assert(n >= 0);
2044 int cond2 = e->v.BoolOp.op == Or;
2045 basicblock *next2 = next;
2046 if (!cond2 != !cond) {
2047 next2 = compiler_new_block(c);
2048 if (next2 == NULL)
2049 return 0;
2050 }
2051 for (i = 0; i < n; ++i) {
2052 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2053 return 0;
2054 }
2055 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2056 return 0;
2057 if (next2 != next)
2058 compiler_use_next_block(c, next2);
2059 return 1;
2060 }
2061 case IfExp_kind: {
2062 basicblock *end, *next2;
2063 end = compiler_new_block(c);
2064 if (end == NULL)
2065 return 0;
2066 next2 = compiler_new_block(c);
2067 if (next2 == NULL)
2068 return 0;
2069 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2070 return 0;
2071 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2072 return 0;
2073 ADDOP_JREL(c, JUMP_FORWARD, end);
2074 compiler_use_next_block(c, next2);
2075 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2076 return 0;
2077 compiler_use_next_block(c, end);
2078 return 1;
2079 }
2080 case Compare_kind: {
2081 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2082 if (n > 0) {
2083 basicblock *cleanup = compiler_new_block(c);
2084 if (cleanup == NULL)
2085 return 0;
2086 VISIT(c, expr, e->v.Compare.left);
2087 for (i = 0; i < n; i++) {
2088 VISIT(c, expr,
2089 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2090 ADDOP(c, DUP_TOP);
2091 ADDOP(c, ROT_THREE);
2092 ADDOP_I(c, COMPARE_OP,
2093 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2094 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2095 NEXT_BLOCK(c);
2096 }
2097 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2098 ADDOP_I(c, COMPARE_OP,
2099 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2100 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2101 basicblock *end = compiler_new_block(c);
2102 if (end == NULL)
2103 return 0;
2104 ADDOP_JREL(c, JUMP_FORWARD, end);
2105 compiler_use_next_block(c, cleanup);
2106 ADDOP(c, POP_TOP);
2107 if (!cond) {
2108 ADDOP_JREL(c, JUMP_FORWARD, next);
2109 }
2110 compiler_use_next_block(c, end);
2111 return 1;
2112 }
2113 /* fallback to general implementation */
2114 break;
2115 }
2116 default:
2117 /* fallback to general implementation */
2118 break;
2119 }
2120
2121 /* general implementation */
2122 VISIT(c, expr, e);
2123 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2124 return 1;
2125}
2126
2127static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002128compiler_ifexp(struct compiler *c, expr_ty e)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 basicblock *end, *next;
2131
2132 assert(e->kind == IfExp_kind);
2133 end = compiler_new_block(c);
2134 if (end == NULL)
2135 return 0;
2136 next = compiler_new_block(c);
2137 if (next == NULL)
2138 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002139 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2140 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 VISIT(c, expr, e->v.IfExp.body);
2142 ADDOP_JREL(c, JUMP_FORWARD, end);
2143 compiler_use_next_block(c, next);
2144 VISIT(c, expr, e->v.IfExp.orelse);
2145 compiler_use_next_block(c, end);
2146 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002147}
2148
2149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150compiler_lambda(struct compiler *c, expr_ty e)
2151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002153 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002155 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 arguments_ty args = e->v.Lambda.args;
2157 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (!name) {
2160 name = PyUnicode_InternFromString("<lambda>");
2161 if (!name)
2162 return 0;
2163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 funcflags = compiler_default_arguments(c, args);
2166 if (funcflags == -1) {
2167 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002169
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002170 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002171 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Make None the first constant, so the lambda can't have a
2175 docstring. */
2176 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2177 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 c->u->u_argcount = asdl_seq_LEN(args->args);
2180 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2181 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2182 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002183 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 }
2185 else {
2186 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002187 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002189 qualname = c->u->u_qualname;
2190 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002192 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002195 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002196 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_DECREF(co);
2198
2199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200}
2201
2202static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203compiler_if(struct compiler *c, stmt_ty s)
2204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 basicblock *end, *next;
2206 int constant;
2207 assert(s->kind == If_kind);
2208 end = compiler_new_block(c);
2209 if (end == NULL)
2210 return 0;
2211
Georg Brandl8334fd92010-12-04 10:26:46 +00002212 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* constant = 0: "if 0"
2214 * constant = 1: "if 1", "if 2", ...
2215 * constant = -1: rest */
2216 if (constant == 0) {
2217 if (s->v.If.orelse)
2218 VISIT_SEQ(c, stmt, s->v.If.orelse);
2219 } else if (constant == 1) {
2220 VISIT_SEQ(c, stmt, s->v.If.body);
2221 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002222 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 next = compiler_new_block(c);
2224 if (next == NULL)
2225 return 0;
2226 }
2227 else
2228 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002229 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2230 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002232 if (asdl_seq_LEN(s->v.If.orelse)) {
2233 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 compiler_use_next_block(c, next);
2235 VISIT_SEQ(c, stmt, s->v.If.orelse);
2236 }
2237 }
2238 compiler_use_next_block(c, end);
2239 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240}
2241
2242static int
2243compiler_for(struct compiler *c, stmt_ty s)
2244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 start = compiler_new_block(c);
2248 cleanup = compiler_new_block(c);
2249 end = compiler_new_block(c);
2250 if (start == NULL || end == NULL || cleanup == NULL)
2251 return 0;
2252 ADDOP_JREL(c, SETUP_LOOP, end);
2253 if (!compiler_push_fblock(c, LOOP, start))
2254 return 0;
2255 VISIT(c, expr, s->v.For.iter);
2256 ADDOP(c, GET_ITER);
2257 compiler_use_next_block(c, start);
2258 ADDOP_JREL(c, FOR_ITER, cleanup);
2259 VISIT(c, expr, s->v.For.target);
2260 VISIT_SEQ(c, stmt, s->v.For.body);
2261 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2262 compiler_use_next_block(c, cleanup);
2263 ADDOP(c, POP_BLOCK);
2264 compiler_pop_fblock(c, LOOP, start);
2265 VISIT_SEQ(c, stmt, s->v.For.orelse);
2266 compiler_use_next_block(c, end);
2267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268}
2269
Yury Selivanov75445082015-05-11 22:57:16 -04002270
2271static int
2272compiler_async_for(struct compiler *c, stmt_ty s)
2273{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002274 _Py_IDENTIFIER(StopAsyncIteration);
2275
Yury Selivanov75445082015-05-11 22:57:16 -04002276 basicblock *try, *except, *end, *after_try, *try_cleanup,
2277 *after_loop, *after_loop_else;
2278
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002279 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2280 if (stop_aiter_error == NULL) {
2281 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002282 }
2283
2284 try = compiler_new_block(c);
2285 except = compiler_new_block(c);
2286 end = compiler_new_block(c);
2287 after_try = compiler_new_block(c);
2288 try_cleanup = compiler_new_block(c);
2289 after_loop = compiler_new_block(c);
2290 after_loop_else = compiler_new_block(c);
2291
2292 if (try == NULL || except == NULL || end == NULL
2293 || after_try == NULL || try_cleanup == NULL)
2294 return 0;
2295
2296 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2297 if (!compiler_push_fblock(c, LOOP, try))
2298 return 0;
2299
2300 VISIT(c, expr, s->v.AsyncFor.iter);
2301 ADDOP(c, GET_AITER);
2302 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2303 ADDOP(c, YIELD_FROM);
2304
2305 compiler_use_next_block(c, try);
2306
2307
2308 ADDOP_JREL(c, SETUP_EXCEPT, except);
2309 if (!compiler_push_fblock(c, EXCEPT, try))
2310 return 0;
2311
2312 ADDOP(c, GET_ANEXT);
2313 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2314 ADDOP(c, YIELD_FROM);
2315 VISIT(c, expr, s->v.AsyncFor.target);
2316 ADDOP(c, POP_BLOCK);
2317 compiler_pop_fblock(c, EXCEPT, try);
2318 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2319
2320
2321 compiler_use_next_block(c, except);
2322 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002323 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002324 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2325 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2326
2327 ADDOP(c, POP_TOP);
2328 ADDOP(c, POP_TOP);
2329 ADDOP(c, POP_TOP);
2330 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2331 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2332 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2333
2334
2335 compiler_use_next_block(c, try_cleanup);
2336 ADDOP(c, END_FINALLY);
2337
2338 compiler_use_next_block(c, after_try);
2339 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2340 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2341
2342 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2343 compiler_pop_fblock(c, LOOP, try);
2344
2345 compiler_use_next_block(c, after_loop);
2346 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2347
2348 compiler_use_next_block(c, after_loop_else);
2349 VISIT_SEQ(c, stmt, s->v.For.orelse);
2350
2351 compiler_use_next_block(c, end);
2352
2353 return 1;
2354}
2355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356static int
2357compiler_while(struct compiler *c, stmt_ty s)
2358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002360 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (constant == 0) {
2363 if (s->v.While.orelse)
2364 VISIT_SEQ(c, stmt, s->v.While.orelse);
2365 return 1;
2366 }
2367 loop = compiler_new_block(c);
2368 end = compiler_new_block(c);
2369 if (constant == -1) {
2370 anchor = compiler_new_block(c);
2371 if (anchor == NULL)
2372 return 0;
2373 }
2374 if (loop == NULL || end == NULL)
2375 return 0;
2376 if (s->v.While.orelse) {
2377 orelse = compiler_new_block(c);
2378 if (orelse == NULL)
2379 return 0;
2380 }
2381 else
2382 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 ADDOP_JREL(c, SETUP_LOOP, end);
2385 compiler_use_next_block(c, loop);
2386 if (!compiler_push_fblock(c, LOOP, loop))
2387 return 0;
2388 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002389 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2390 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 }
2392 VISIT_SEQ(c, stmt, s->v.While.body);
2393 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* XXX should the two POP instructions be in a separate block
2396 if there is no else clause ?
2397 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002399 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002401 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 compiler_pop_fblock(c, LOOP, loop);
2403 if (orelse != NULL) /* what if orelse is just pass? */
2404 VISIT_SEQ(c, stmt, s->v.While.orelse);
2405 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408}
2409
2410static int
2411compiler_continue(struct compiler *c)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2414 static const char IN_FINALLY_ERROR_MSG[] =
2415 "'continue' not supported inside 'finally' clause";
2416 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (!c->u->u_nfblocks)
2419 return compiler_error(c, LOOP_ERROR_MSG);
2420 i = c->u->u_nfblocks - 1;
2421 switch (c->u->u_fblock[i].fb_type) {
2422 case LOOP:
2423 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2424 break;
2425 case EXCEPT:
2426 case FINALLY_TRY:
2427 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2428 /* Prevent continue anywhere under a finally
2429 even if hidden in a sub-try or except. */
2430 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2431 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2432 }
2433 if (i == -1)
2434 return compiler_error(c, LOOP_ERROR_MSG);
2435 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2436 break;
2437 case FINALLY_END:
2438 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442}
2443
2444/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445
2446 SETUP_FINALLY L
2447 <code for body>
2448 POP_BLOCK
2449 LOAD_CONST <None>
2450 L: <code for finalbody>
2451 END_FINALLY
2452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453 The special instructions use the block stack. Each block
2454 stack entry contains the instruction that created it (here
2455 SETUP_FINALLY), the level of the value stack at the time the
2456 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 Pushes the current value stack level and the label
2460 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 Pops en entry from the block stack, and pops the value
2463 stack until its level is the same as indicated on the
2464 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Pops a variable number of entries from the *value* stack
2467 and re-raises the exception they specify. The number of
2468 entries popped depends on the (pseudo) exception type.
2469
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 The block stack is unwound when an exception is raised:
2471 when a SETUP_FINALLY entry is found, the exception is pushed
2472 onto the value stack (and the exception condition is cleared),
2473 and the interpreter jumps to the label gotten from the block
2474 stack.
2475*/
2476
2477static int
2478compiler_try_finally(struct compiler *c, stmt_ty s)
2479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 basicblock *body, *end;
2481 body = compiler_new_block(c);
2482 end = compiler_new_block(c);
2483 if (body == NULL || end == NULL)
2484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 ADDOP_JREL(c, SETUP_FINALLY, end);
2487 compiler_use_next_block(c, body);
2488 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2489 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002490 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2491 if (!compiler_try_except(c, s))
2492 return 0;
2493 }
2494 else {
2495 VISIT_SEQ(c, stmt, s->v.Try.body);
2496 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 ADDOP(c, POP_BLOCK);
2498 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2501 compiler_use_next_block(c, end);
2502 if (!compiler_push_fblock(c, FINALLY_END, end))
2503 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002504 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 ADDOP(c, END_FINALLY);
2506 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509}
2510
2511/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002512 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 (The contents of the value stack is shown in [], with the top
2514 at the right; 'tb' is trace-back info, 'val' the exception's
2515 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516
2517 Value stack Label Instruction Argument
2518 [] SETUP_EXCEPT L1
2519 [] <code for S>
2520 [] POP_BLOCK
2521 [] JUMP_FORWARD L0
2522
2523 [tb, val, exc] L1: DUP )
2524 [tb, val, exc, exc] <evaluate E1> )
2525 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2526 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2527 [tb, val, exc] POP
2528 [tb, val] <assign to V1> (or POP if no V1)
2529 [tb] POP
2530 [] <code for S1>
2531 JUMP_FORWARD L0
2532
2533 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 .............................etc.......................
2535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2537
2538 [] L0: <next statement>
2539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 Of course, parts are not generated if Vi or Ei is not present.
2541*/
2542static int
2543compiler_try_except(struct compiler *c, stmt_ty s)
2544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002546 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 body = compiler_new_block(c);
2549 except = compiler_new_block(c);
2550 orelse = compiler_new_block(c);
2551 end = compiler_new_block(c);
2552 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2553 return 0;
2554 ADDOP_JREL(c, SETUP_EXCEPT, except);
2555 compiler_use_next_block(c, body);
2556 if (!compiler_push_fblock(c, EXCEPT, body))
2557 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002558 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 ADDOP(c, POP_BLOCK);
2560 compiler_pop_fblock(c, EXCEPT, body);
2561 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002562 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 compiler_use_next_block(c, except);
2564 for (i = 0; i < n; i++) {
2565 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002566 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 if (!handler->v.ExceptHandler.type && i < n-1)
2568 return compiler_error(c, "default 'except:' must be last");
2569 c->u->u_lineno_set = 0;
2570 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002571 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 except = compiler_new_block(c);
2573 if (except == NULL)
2574 return 0;
2575 if (handler->v.ExceptHandler.type) {
2576 ADDOP(c, DUP_TOP);
2577 VISIT(c, expr, handler->v.ExceptHandler.type);
2578 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2579 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2580 }
2581 ADDOP(c, POP_TOP);
2582 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002583 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002584
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002585 cleanup_end = compiler_new_block(c);
2586 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002587 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002588 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002589
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002590 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2591 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002593 /*
2594 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002595 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002596 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002597 try:
2598 # body
2599 finally:
2600 name = None
2601 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002602 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002604 /* second try: */
2605 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2606 compiler_use_next_block(c, cleanup_body);
2607 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2608 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002610 /* second # body */
2611 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2612 ADDOP(c, POP_BLOCK);
2613 ADDOP(c, POP_EXCEPT);
2614 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002616 /* finally: */
2617 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2618 compiler_use_next_block(c, cleanup_end);
2619 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2620 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002622 /* name = None */
2623 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2624 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002626 /* del name */
2627 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002629 ADDOP(c, END_FINALLY);
2630 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 }
2632 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002633 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002635 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002636 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002637 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638
Guido van Rossumb940e112007-01-10 16:19:56 +00002639 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002640 ADDOP(c, POP_TOP);
2641 compiler_use_next_block(c, cleanup_body);
2642 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2643 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002645 ADDOP(c, POP_EXCEPT);
2646 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 }
2648 ADDOP_JREL(c, JUMP_FORWARD, end);
2649 compiler_use_next_block(c, except);
2650 }
2651 ADDOP(c, END_FINALLY);
2652 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002653 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 compiler_use_next_block(c, end);
2655 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656}
2657
2658static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002659compiler_try(struct compiler *c, stmt_ty s) {
2660 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2661 return compiler_try_finally(c, s);
2662 else
2663 return compiler_try_except(c, s);
2664}
2665
2666
2667static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668compiler_import_as(struct compiler *c, identifier name, identifier asname)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* The IMPORT_NAME opcode was already generated. This function
2671 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002674 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002676 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2677 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002679 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002680 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002682 while (1) {
2683 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002685 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002686 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002687 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002688 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002690 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002691 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002693 if (dot == -1) {
2694 break;
2695 }
2696 ADDOP(c, ROT_TWO);
2697 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002699 if (!compiler_nameop(c, asname, Store)) {
2700 return 0;
2701 }
2702 ADDOP(c, POP_TOP);
2703 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 }
2705 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706}
2707
2708static int
2709compiler_import(struct compiler *c, stmt_ty s)
2710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 /* The Import node stores a module name like a.b.c as a single
2712 string. This is convenient for all cases except
2713 import a.b.c as d
2714 where we need to parse that string to extract the individual
2715 module names.
2716 XXX Perhaps change the representation to make this case simpler?
2717 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002718 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 for (i = 0; i < n; i++) {
2721 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2722 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002724 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2726 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 if (alias->asname) {
2729 r = compiler_import_as(c, alias->name, alias->asname);
2730 if (!r)
2731 return r;
2732 }
2733 else {
2734 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 Py_ssize_t dot = PyUnicode_FindChar(
2736 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002737 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002738 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002739 if (tmp == NULL)
2740 return 0;
2741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002743 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 Py_DECREF(tmp);
2745 }
2746 if (!r)
2747 return r;
2748 }
2749 }
2750 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751}
2752
2753static int
2754compiler_from_import(struct compiler *c, stmt_ty s)
2755{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002756 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 PyObject *names = PyTuple_New(n);
2759 PyObject *level;
2760 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 if (!empty_string) {
2763 empty_string = PyUnicode_FromString("");
2764 if (!empty_string)
2765 return 0;
2766 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 if (!names)
2769 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 level = PyLong_FromLong(s->v.ImportFrom.level);
2772 if (!level) {
2773 Py_DECREF(names);
2774 return 0;
2775 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 /* build up the names */
2778 for (i = 0; i < n; i++) {
2779 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2780 Py_INCREF(alias->name);
2781 PyTuple_SET_ITEM(names, i, alias->name);
2782 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002785 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 Py_DECREF(level);
2787 Py_DECREF(names);
2788 return compiler_error(c, "from __future__ imports must occur "
2789 "at the beginning of the file");
2790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 ADDOP_O(c, LOAD_CONST, level, consts);
2793 Py_DECREF(level);
2794 ADDOP_O(c, LOAD_CONST, names, consts);
2795 Py_DECREF(names);
2796 if (s->v.ImportFrom.module) {
2797 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2798 }
2799 else {
2800 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2801 }
2802 for (i = 0; i < n; i++) {
2803 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2804 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 assert(n == 1);
2808 ADDOP(c, IMPORT_STAR);
2809 return 1;
2810 }
2811
2812 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2813 store_name = alias->name;
2814 if (alias->asname)
2815 store_name = alias->asname;
2816
2817 if (!compiler_nameop(c, store_name, Store)) {
2818 Py_DECREF(names);
2819 return 0;
2820 }
2821 }
2822 /* remove imported module */
2823 ADDOP(c, POP_TOP);
2824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825}
2826
2827static int
2828compiler_assert(struct compiler *c, stmt_ty s)
2829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 static PyObject *assertion_error = NULL;
2831 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002832 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Georg Brandl8334fd92010-12-04 10:26:46 +00002834 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return 1;
2836 if (assertion_error == NULL) {
2837 assertion_error = PyUnicode_InternFromString("AssertionError");
2838 if (assertion_error == NULL)
2839 return 0;
2840 }
2841 if (s->v.Assert.test->kind == Tuple_kind &&
2842 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002843 msg = PyUnicode_FromString("assertion is always true, "
2844 "perhaps remove parentheses?");
2845 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002847 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2848 c->c_filename, c->u->u_lineno,
2849 NULL, NULL) == -1) {
2850 Py_DECREF(msg);
2851 return 0;
2852 }
2853 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 end = compiler_new_block(c);
2856 if (end == NULL)
2857 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002858 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2859 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2861 if (s->v.Assert.msg) {
2862 VISIT(c, expr, s->v.Assert.msg);
2863 ADDOP_I(c, CALL_FUNCTION, 1);
2864 }
2865 ADDOP_I(c, RAISE_VARARGS, 1);
2866 compiler_use_next_block(c, end);
2867 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868}
2869
2870static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002871compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2872{
2873 if (c->c_interactive && c->c_nestlevel <= 1) {
2874 VISIT(c, expr, value);
2875 ADDOP(c, PRINT_EXPR);
2876 return 1;
2877 }
2878
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002879 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002880 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002881 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002882 }
2883
2884 VISIT(c, expr, value);
2885 ADDOP(c, POP_TOP);
2886 return 1;
2887}
2888
2889static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890compiler_visit_stmt(struct compiler *c, stmt_ty s)
2891{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002892 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 /* Always assign a lineno to the next instruction for a stmt. */
2895 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002896 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 switch (s->kind) {
2900 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002901 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 case ClassDef_kind:
2903 return compiler_class(c, s);
2904 case Return_kind:
2905 if (c->u->u_ste->ste_type != FunctionBlock)
2906 return compiler_error(c, "'return' outside function");
2907 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002908 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2909 return compiler_error(
2910 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 VISIT(c, expr, s->v.Return.value);
2912 }
2913 else
2914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2915 ADDOP(c, RETURN_VALUE);
2916 break;
2917 case Delete_kind:
2918 VISIT_SEQ(c, expr, s->v.Delete.targets)
2919 break;
2920 case Assign_kind:
2921 n = asdl_seq_LEN(s->v.Assign.targets);
2922 VISIT(c, expr, s->v.Assign.value);
2923 for (i = 0; i < n; i++) {
2924 if (i < n - 1)
2925 ADDOP(c, DUP_TOP);
2926 VISIT(c, expr,
2927 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2928 }
2929 break;
2930 case AugAssign_kind:
2931 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002932 case AnnAssign_kind:
2933 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 case For_kind:
2935 return compiler_for(c, s);
2936 case While_kind:
2937 return compiler_while(c, s);
2938 case If_kind:
2939 return compiler_if(c, s);
2940 case Raise_kind:
2941 n = 0;
2942 if (s->v.Raise.exc) {
2943 VISIT(c, expr, s->v.Raise.exc);
2944 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002945 if (s->v.Raise.cause) {
2946 VISIT(c, expr, s->v.Raise.cause);
2947 n++;
2948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002950 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002952 case Try_kind:
2953 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 case Assert_kind:
2955 return compiler_assert(c, s);
2956 case Import_kind:
2957 return compiler_import(c, s);
2958 case ImportFrom_kind:
2959 return compiler_from_import(c, s);
2960 case Global_kind:
2961 case Nonlocal_kind:
2962 break;
2963 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002964 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 case Pass_kind:
2966 break;
2967 case Break_kind:
2968 if (!compiler_in_loop(c))
2969 return compiler_error(c, "'break' outside loop");
2970 ADDOP(c, BREAK_LOOP);
2971 break;
2972 case Continue_kind:
2973 return compiler_continue(c);
2974 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002975 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002976 case AsyncFunctionDef_kind:
2977 return compiler_function(c, s, 1);
2978 case AsyncWith_kind:
2979 return compiler_async_with(c, s, 0);
2980 case AsyncFor_kind:
2981 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 }
Yury Selivanov75445082015-05-11 22:57:16 -04002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985}
2986
2987static int
2988unaryop(unaryop_ty op)
2989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 switch (op) {
2991 case Invert:
2992 return UNARY_INVERT;
2993 case Not:
2994 return UNARY_NOT;
2995 case UAdd:
2996 return UNARY_POSITIVE;
2997 case USub:
2998 return UNARY_NEGATIVE;
2999 default:
3000 PyErr_Format(PyExc_SystemError,
3001 "unary op %d should not be possible", op);
3002 return 0;
3003 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004}
3005
3006static int
3007binop(struct compiler *c, operator_ty op)
3008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 switch (op) {
3010 case Add:
3011 return BINARY_ADD;
3012 case Sub:
3013 return BINARY_SUBTRACT;
3014 case Mult:
3015 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003016 case MatMult:
3017 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 case Div:
3019 return BINARY_TRUE_DIVIDE;
3020 case Mod:
3021 return BINARY_MODULO;
3022 case Pow:
3023 return BINARY_POWER;
3024 case LShift:
3025 return BINARY_LSHIFT;
3026 case RShift:
3027 return BINARY_RSHIFT;
3028 case BitOr:
3029 return BINARY_OR;
3030 case BitXor:
3031 return BINARY_XOR;
3032 case BitAnd:
3033 return BINARY_AND;
3034 case FloorDiv:
3035 return BINARY_FLOOR_DIVIDE;
3036 default:
3037 PyErr_Format(PyExc_SystemError,
3038 "binary op %d should not be possible", op);
3039 return 0;
3040 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041}
3042
3043static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044inplace_binop(struct compiler *c, operator_ty op)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 switch (op) {
3047 case Add:
3048 return INPLACE_ADD;
3049 case Sub:
3050 return INPLACE_SUBTRACT;
3051 case Mult:
3052 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003053 case MatMult:
3054 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 case Div:
3056 return INPLACE_TRUE_DIVIDE;
3057 case Mod:
3058 return INPLACE_MODULO;
3059 case Pow:
3060 return INPLACE_POWER;
3061 case LShift:
3062 return INPLACE_LSHIFT;
3063 case RShift:
3064 return INPLACE_RSHIFT;
3065 case BitOr:
3066 return INPLACE_OR;
3067 case BitXor:
3068 return INPLACE_XOR;
3069 case BitAnd:
3070 return INPLACE_AND;
3071 case FloorDiv:
3072 return INPLACE_FLOOR_DIVIDE;
3073 default:
3074 PyErr_Format(PyExc_SystemError,
3075 "inplace binary op %d should not be possible", op);
3076 return 0;
3077 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078}
3079
3080static int
3081compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3082{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003083 int op, scope;
3084 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 PyObject *dict = c->u->u_names;
3088 PyObject *mangled;
3089 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 mangled = _Py_Mangle(c->u->u_private, name);
3092 if (!mangled)
3093 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003094
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003095 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3096 !_PyUnicode_EqualToASCIIString(name, "True") &&
3097 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 op = 0;
3100 optype = OP_NAME;
3101 scope = PyST_GetScope(c->u->u_ste, mangled);
3102 switch (scope) {
3103 case FREE:
3104 dict = c->u->u_freevars;
3105 optype = OP_DEREF;
3106 break;
3107 case CELL:
3108 dict = c->u->u_cellvars;
3109 optype = OP_DEREF;
3110 break;
3111 case LOCAL:
3112 if (c->u->u_ste->ste_type == FunctionBlock)
3113 optype = OP_FAST;
3114 break;
3115 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003116 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 optype = OP_GLOBAL;
3118 break;
3119 case GLOBAL_EXPLICIT:
3120 optype = OP_GLOBAL;
3121 break;
3122 default:
3123 /* scope can be 0 */
3124 break;
3125 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003128 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 switch (optype) {
3131 case OP_DEREF:
3132 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003133 case Load:
3134 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3135 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 case Store: op = STORE_DEREF; break;
3137 case AugLoad:
3138 case AugStore:
3139 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003140 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 case Param:
3142 default:
3143 PyErr_SetString(PyExc_SystemError,
3144 "param invalid for deref variable");
3145 return 0;
3146 }
3147 break;
3148 case OP_FAST:
3149 switch (ctx) {
3150 case Load: op = LOAD_FAST; break;
3151 case Store: op = STORE_FAST; break;
3152 case Del: op = DELETE_FAST; break;
3153 case AugLoad:
3154 case AugStore:
3155 break;
3156 case Param:
3157 default:
3158 PyErr_SetString(PyExc_SystemError,
3159 "param invalid for local variable");
3160 return 0;
3161 }
3162 ADDOP_O(c, op, mangled, varnames);
3163 Py_DECREF(mangled);
3164 return 1;
3165 case OP_GLOBAL:
3166 switch (ctx) {
3167 case Load: op = LOAD_GLOBAL; break;
3168 case Store: op = STORE_GLOBAL; break;
3169 case Del: op = DELETE_GLOBAL; break;
3170 case AugLoad:
3171 case AugStore:
3172 break;
3173 case Param:
3174 default:
3175 PyErr_SetString(PyExc_SystemError,
3176 "param invalid for global variable");
3177 return 0;
3178 }
3179 break;
3180 case OP_NAME:
3181 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003182 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 case Store: op = STORE_NAME; break;
3184 case Del: op = DELETE_NAME; break;
3185 case AugLoad:
3186 case AugStore:
3187 break;
3188 case Param:
3189 default:
3190 PyErr_SetString(PyExc_SystemError,
3191 "param invalid for name variable");
3192 return 0;
3193 }
3194 break;
3195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 assert(op);
3198 arg = compiler_add_o(c, dict, mangled);
3199 Py_DECREF(mangled);
3200 if (arg < 0)
3201 return 0;
3202 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203}
3204
3205static int
3206compiler_boolop(struct compiler *c, expr_ty e)
3207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003209 int jumpi;
3210 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 assert(e->kind == BoolOp_kind);
3214 if (e->v.BoolOp.op == And)
3215 jumpi = JUMP_IF_FALSE_OR_POP;
3216 else
3217 jumpi = JUMP_IF_TRUE_OR_POP;
3218 end = compiler_new_block(c);
3219 if (end == NULL)
3220 return 0;
3221 s = e->v.BoolOp.values;
3222 n = asdl_seq_LEN(s) - 1;
3223 assert(n >= 0);
3224 for (i = 0; i < n; ++i) {
3225 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3226 ADDOP_JABS(c, jumpi, end);
3227 }
3228 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3229 compiler_use_next_block(c, end);
3230 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231}
3232
3233static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003234starunpack_helper(struct compiler *c, asdl_seq *elts,
3235 int single_op, int inner_op, int outer_op)
3236{
3237 Py_ssize_t n = asdl_seq_LEN(elts);
3238 Py_ssize_t i, nsubitems = 0, nseen = 0;
3239 for (i = 0; i < n; i++) {
3240 expr_ty elt = asdl_seq_GET(elts, i);
3241 if (elt->kind == Starred_kind) {
3242 if (nseen) {
3243 ADDOP_I(c, inner_op, nseen);
3244 nseen = 0;
3245 nsubitems++;
3246 }
3247 VISIT(c, expr, elt->v.Starred.value);
3248 nsubitems++;
3249 }
3250 else {
3251 VISIT(c, expr, elt);
3252 nseen++;
3253 }
3254 }
3255 if (nsubitems) {
3256 if (nseen) {
3257 ADDOP_I(c, inner_op, nseen);
3258 nsubitems++;
3259 }
3260 ADDOP_I(c, outer_op, nsubitems);
3261 }
3262 else
3263 ADDOP_I(c, single_op, nseen);
3264 return 1;
3265}
3266
3267static int
3268assignment_helper(struct compiler *c, asdl_seq *elts)
3269{
3270 Py_ssize_t n = asdl_seq_LEN(elts);
3271 Py_ssize_t i;
3272 int seen_star = 0;
3273 for (i = 0; i < n; i++) {
3274 expr_ty elt = asdl_seq_GET(elts, i);
3275 if (elt->kind == Starred_kind && !seen_star) {
3276 if ((i >= (1 << 8)) ||
3277 (n-i-1 >= (INT_MAX >> 8)))
3278 return compiler_error(c,
3279 "too many expressions in "
3280 "star-unpacking assignment");
3281 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3282 seen_star = 1;
3283 asdl_seq_SET(elts, i, elt->v.Starred.value);
3284 }
3285 else if (elt->kind == Starred_kind) {
3286 return compiler_error(c,
3287 "two starred expressions in assignment");
3288 }
3289 }
3290 if (!seen_star) {
3291 ADDOP_I(c, UNPACK_SEQUENCE, n);
3292 }
3293 VISIT_SEQ(c, expr, elts);
3294 return 1;
3295}
3296
3297static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298compiler_list(struct compiler *c, expr_ty e)
3299{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003300 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003302 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003304 else if (e->v.List.ctx == Load) {
3305 return starunpack_helper(c, elts,
3306 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003308 else
3309 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311}
3312
3313static int
3314compiler_tuple(struct compiler *c, expr_ty e)
3315{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003316 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003318 return assignment_helper(c, elts);
3319 }
3320 else if (e->v.Tuple.ctx == Load) {
3321 return starunpack_helper(c, elts,
3322 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3323 }
3324 else
3325 VISIT_SEQ(c, expr, elts);
3326 return 1;
3327}
3328
3329static int
3330compiler_set(struct compiler *c, expr_ty e)
3331{
3332 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3333 BUILD_SET, BUILD_SET_UNPACK);
3334}
3335
3336static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003337are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3338{
3339 Py_ssize_t i;
3340 for (i = begin; i < end; i++) {
3341 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3342 if (key == NULL || !is_const(key))
3343 return 0;
3344 }
3345 return 1;
3346}
3347
3348static int
3349compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3350{
3351 Py_ssize_t i, n = end - begin;
3352 PyObject *keys, *key;
3353 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3354 for (i = begin; i < end; i++) {
3355 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3356 }
3357 keys = PyTuple_New(n);
3358 if (keys == NULL) {
3359 return 0;
3360 }
3361 for (i = begin; i < end; i++) {
3362 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3363 Py_INCREF(key);
3364 PyTuple_SET_ITEM(keys, i - begin, key);
3365 }
3366 ADDOP_N(c, LOAD_CONST, keys, consts);
3367 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3368 }
3369 else {
3370 for (i = begin; i < end; i++) {
3371 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3372 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3373 }
3374 ADDOP_I(c, BUILD_MAP, n);
3375 }
3376 return 1;
3377}
3378
3379static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003380compiler_dict(struct compiler *c, expr_ty e)
3381{
Victor Stinner976bb402016-03-23 11:36:19 +01003382 Py_ssize_t i, n, elements;
3383 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003384 int is_unpacking = 0;
3385 n = asdl_seq_LEN(e->v.Dict.values);
3386 containers = 0;
3387 elements = 0;
3388 for (i = 0; i < n; i++) {
3389 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3390 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003391 if (!compiler_subdict(c, e, i - elements, i))
3392 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003393 containers++;
3394 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003396 if (is_unpacking) {
3397 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3398 containers++;
3399 }
3400 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003401 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 }
3403 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003404 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003405 if (!compiler_subdict(c, e, n - elements, n))
3406 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003407 containers++;
3408 }
3409 /* If there is more than one dict, they need to be merged into a new
3410 * dict. If there is one dict and it's an unpacking, then it needs
3411 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003412 if (containers > 1 || is_unpacking) {
3413 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 }
3415 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003416}
3417
3418static int
3419compiler_compare(struct compiler *c, expr_ty e)
3420{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003421 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3425 VISIT(c, expr, e->v.Compare.left);
3426 n = asdl_seq_LEN(e->v.Compare.ops);
3427 assert(n > 0);
3428 if (n > 1) {
3429 cleanup = compiler_new_block(c);
3430 if (cleanup == NULL)
3431 return 0;
3432 VISIT(c, expr,
3433 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3434 }
3435 for (i = 1; i < n; i++) {
3436 ADDOP(c, DUP_TOP);
3437 ADDOP(c, ROT_THREE);
3438 ADDOP_I(c, COMPARE_OP,
3439 cmpop((cmpop_ty)(asdl_seq_GET(
3440 e->v.Compare.ops, i - 1))));
3441 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3442 NEXT_BLOCK(c);
3443 if (i < (n - 1))
3444 VISIT(c, expr,
3445 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3446 }
3447 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3448 ADDOP_I(c, COMPARE_OP,
3449 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3450 if (n > 1) {
3451 basicblock *end = compiler_new_block(c);
3452 if (end == NULL)
3453 return 0;
3454 ADDOP_JREL(c, JUMP_FORWARD, end);
3455 compiler_use_next_block(c, cleanup);
3456 ADDOP(c, ROT_TWO);
3457 ADDOP(c, POP_TOP);
3458 compiler_use_next_block(c, end);
3459 }
3460 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461}
3462
3463static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003464maybe_optimize_method_call(struct compiler *c, expr_ty e)
3465{
3466 Py_ssize_t argsl, i;
3467 expr_ty meth = e->v.Call.func;
3468 asdl_seq *args = e->v.Call.args;
3469
3470 /* Check that the call node is an attribute access, and that
3471 the call doesn't have keyword parameters. */
3472 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3473 asdl_seq_LEN(e->v.Call.keywords))
3474 return -1;
3475
3476 /* Check that there are no *varargs types of arguments. */
3477 argsl = asdl_seq_LEN(args);
3478 for (i = 0; i < argsl; i++) {
3479 expr_ty elt = asdl_seq_GET(args, i);
3480 if (elt->kind == Starred_kind) {
3481 return -1;
3482 }
3483 }
3484
3485 /* Alright, we can optimize the code. */
3486 VISIT(c, expr, meth->v.Attribute.value);
3487 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3488 VISIT_SEQ(c, expr, e->v.Call.args);
3489 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3490 return 1;
3491}
3492
3493static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494compiler_call(struct compiler *c, expr_ty e)
3495{
Yury Selivanovf2392132016-12-13 19:03:51 -05003496 if (maybe_optimize_method_call(c, e) > 0)
3497 return 1;
3498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 VISIT(c, expr, e->v.Call.func);
3500 return compiler_call_helper(c, 0,
3501 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003502 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003503}
3504
Eric V. Smith235a6f02015-09-19 14:51:32 -04003505static int
3506compiler_joined_str(struct compiler *c, expr_ty e)
3507{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003508 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003509 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3510 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003511 return 1;
3512}
3513
Eric V. Smitha78c7952015-11-03 12:45:05 -05003514/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003515static int
3516compiler_formatted_value(struct compiler *c, expr_ty e)
3517{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003518 /* Our oparg encodes 2 pieces of information: the conversion
3519 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003520
Eric V. Smitha78c7952015-11-03 12:45:05 -05003521 Convert the conversion char to 2 bits:
3522 None: 000 0x0 FVC_NONE
3523 !s : 001 0x1 FVC_STR
3524 !r : 010 0x2 FVC_REPR
3525 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003526
Eric V. Smitha78c7952015-11-03 12:45:05 -05003527 next bit is whether or not we have a format spec:
3528 yes : 100 0x4
3529 no : 000 0x0
3530 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003531
Eric V. Smitha78c7952015-11-03 12:45:05 -05003532 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003533
Eric V. Smitha78c7952015-11-03 12:45:05 -05003534 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003535 VISIT(c, expr, e->v.FormattedValue.value);
3536
Eric V. Smitha78c7952015-11-03 12:45:05 -05003537 switch (e->v.FormattedValue.conversion) {
3538 case 's': oparg = FVC_STR; break;
3539 case 'r': oparg = FVC_REPR; break;
3540 case 'a': oparg = FVC_ASCII; break;
3541 case -1: oparg = FVC_NONE; break;
3542 default:
3543 PyErr_SetString(PyExc_SystemError,
3544 "Unrecognized conversion character");
3545 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003546 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003547 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003548 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003549 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003550 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003551 }
3552
Eric V. Smitha78c7952015-11-03 12:45:05 -05003553 /* And push our opcode and oparg */
3554 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003555 return 1;
3556}
3557
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003558static int
3559compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3560{
3561 Py_ssize_t i, n = end - begin;
3562 keyword_ty kw;
3563 PyObject *keys, *key;
3564 assert(n > 0);
3565 if (n > 1) {
3566 for (i = begin; i < end; i++) {
3567 kw = asdl_seq_GET(keywords, i);
3568 VISIT(c, expr, kw->value);
3569 }
3570 keys = PyTuple_New(n);
3571 if (keys == NULL) {
3572 return 0;
3573 }
3574 for (i = begin; i < end; i++) {
3575 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3576 Py_INCREF(key);
3577 PyTuple_SET_ITEM(keys, i - begin, key);
3578 }
3579 ADDOP_N(c, LOAD_CONST, keys, consts);
3580 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3581 }
3582 else {
3583 /* a for loop only executes once */
3584 for (i = begin; i < end; i++) {
3585 kw = asdl_seq_GET(keywords, i);
3586 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3587 VISIT(c, expr, kw->value);
3588 }
3589 ADDOP_I(c, BUILD_MAP, n);
3590 }
3591 return 1;
3592}
3593
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003594/* shared code between compiler_call and compiler_class */
3595static int
3596compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003597 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003598 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003599 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003600{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003601 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003602 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003603
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003604 /* the number of tuples and dictionaries on the stack */
3605 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3606
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003607 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003608 nkwelts = asdl_seq_LEN(keywords);
3609
3610 for (i = 0; i < nkwelts; i++) {
3611 keyword_ty kw = asdl_seq_GET(keywords, i);
3612 if (kw->arg == NULL) {
3613 mustdictunpack = 1;
3614 break;
3615 }
3616 }
3617
3618 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003619 for (i = 0; i < nelts; i++) {
3620 expr_ty elt = asdl_seq_GET(args, i);
3621 if (elt->kind == Starred_kind) {
3622 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003623 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003624 if (nseen) {
3625 ADDOP_I(c, BUILD_TUPLE, nseen);
3626 nseen = 0;
3627 nsubargs++;
3628 }
3629 VISIT(c, expr, elt->v.Starred.value);
3630 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003631 }
3632 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003633 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003634 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003637
3638 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003639 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003640 if (nseen) {
3641 /* Pack up any trailing positional arguments. */
3642 ADDOP_I(c, BUILD_TUPLE, nseen);
3643 nsubargs++;
3644 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003645 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003646 /* If we ended up with more than one stararg, we need
3647 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003648 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003649 }
3650 else if (nsubargs == 0) {
3651 ADDOP_I(c, BUILD_TUPLE, 0);
3652 }
3653 nseen = 0; /* the number of keyword arguments on the stack following */
3654 for (i = 0; i < nkwelts; i++) {
3655 keyword_ty kw = asdl_seq_GET(keywords, i);
3656 if (kw->arg == NULL) {
3657 /* A keyword argument unpacking. */
3658 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003659 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3660 return 0;
3661 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003662 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003663 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003664 VISIT(c, expr, kw->value);
3665 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003666 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003667 else {
3668 nseen++;
3669 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003670 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003671 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003672 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003673 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003674 return 0;
3675 nsubkwargs++;
3676 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003677 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003678 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003679 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003680 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003681 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3682 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003684 else if (nkwelts) {
3685 PyObject *names;
3686 VISIT_SEQ(c, keyword, keywords);
3687 names = PyTuple_New(nkwelts);
3688 if (names == NULL) {
3689 return 0;
3690 }
3691 for (i = 0; i < nkwelts; i++) {
3692 keyword_ty kw = asdl_seq_GET(keywords, i);
3693 Py_INCREF(kw->arg);
3694 PyTuple_SET_ITEM(names, i, kw->arg);
3695 }
3696 ADDOP_N(c, LOAD_CONST, names, consts);
3697 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3698 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003700 else {
3701 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3702 return 1;
3703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704}
3705
Nick Coghlan650f0d02007-04-15 12:05:43 +00003706
3707/* List and set comprehensions and generator expressions work by creating a
3708 nested function to perform the actual iteration. This means that the
3709 iteration variables don't leak into the current scope.
3710 The defined function is called immediately following its definition, with the
3711 result of that call being the result of the expression.
3712 The LC/SC version returns the populated container, while the GE version is
3713 flagged in symtable.c as a generator, so it returns the generator object
3714 when the function is called.
3715 This code *knows* that the loop cannot contain break, continue, or return,
3716 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3717
3718 Possible cleanups:
3719 - iterate over the generator sequence instead of using recursion
3720*/
3721
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003722
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724compiler_comprehension_generator(struct compiler *c,
3725 asdl_seq *generators, int gen_index,
3726 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003728 comprehension_ty gen;
3729 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3730 if (gen->is_async) {
3731 return compiler_async_comprehension_generator(
3732 c, generators, gen_index, elt, val, type);
3733 } else {
3734 return compiler_sync_comprehension_generator(
3735 c, generators, gen_index, elt, val, type);
3736 }
3737}
3738
3739static int
3740compiler_sync_comprehension_generator(struct compiler *c,
3741 asdl_seq *generators, int gen_index,
3742 expr_ty elt, expr_ty val, int type)
3743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 /* generate code for the iterator, then each of the ifs,
3745 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 comprehension_ty gen;
3748 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003749 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 start = compiler_new_block(c);
3752 skip = compiler_new_block(c);
3753 if_cleanup = compiler_new_block(c);
3754 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3757 anchor == NULL)
3758 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 if (gen_index == 0) {
3763 /* Receive outermost iter as an implicit argument */
3764 c->u->u_argcount = 1;
3765 ADDOP_I(c, LOAD_FAST, 0);
3766 }
3767 else {
3768 /* Sub-iter - calculate on the fly */
3769 VISIT(c, expr, gen->iter);
3770 ADDOP(c, GET_ITER);
3771 }
3772 compiler_use_next_block(c, start);
3773 ADDOP_JREL(c, FOR_ITER, anchor);
3774 NEXT_BLOCK(c);
3775 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 /* XXX this needs to be cleaned up...a lot! */
3778 n = asdl_seq_LEN(gen->ifs);
3779 for (i = 0; i < n; i++) {
3780 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003781 if (!compiler_jump_if(c, e, if_cleanup, 0))
3782 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 NEXT_BLOCK(c);
3784 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 if (++gen_index < asdl_seq_LEN(generators))
3787 if (!compiler_comprehension_generator(c,
3788 generators, gen_index,
3789 elt, val, type))
3790 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 /* only append after the last for generator */
3793 if (gen_index >= asdl_seq_LEN(generators)) {
3794 /* comprehension specific code */
3795 switch (type) {
3796 case COMP_GENEXP:
3797 VISIT(c, expr, elt);
3798 ADDOP(c, YIELD_VALUE);
3799 ADDOP(c, POP_TOP);
3800 break;
3801 case COMP_LISTCOMP:
3802 VISIT(c, expr, elt);
3803 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3804 break;
3805 case COMP_SETCOMP:
3806 VISIT(c, expr, elt);
3807 ADDOP_I(c, SET_ADD, gen_index + 1);
3808 break;
3809 case COMP_DICTCOMP:
3810 /* With 'd[k] = v', v is evaluated before k, so we do
3811 the same. */
3812 VISIT(c, expr, val);
3813 VISIT(c, expr, elt);
3814 ADDOP_I(c, MAP_ADD, gen_index + 1);
3815 break;
3816 default:
3817 return 0;
3818 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 compiler_use_next_block(c, skip);
3821 }
3822 compiler_use_next_block(c, if_cleanup);
3823 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3824 compiler_use_next_block(c, anchor);
3825
3826 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827}
3828
3829static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003830compiler_async_comprehension_generator(struct compiler *c,
3831 asdl_seq *generators, int gen_index,
3832 expr_ty elt, expr_ty val, int type)
3833{
3834 _Py_IDENTIFIER(StopAsyncIteration);
3835
3836 comprehension_ty gen;
3837 basicblock *anchor, *skip, *if_cleanup, *try,
3838 *after_try, *except, *try_cleanup;
3839 Py_ssize_t i, n;
3840
3841 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3842 if (stop_aiter_error == NULL) {
3843 return 0;
3844 }
3845
3846 try = compiler_new_block(c);
3847 after_try = compiler_new_block(c);
3848 try_cleanup = compiler_new_block(c);
3849 except = compiler_new_block(c);
3850 skip = compiler_new_block(c);
3851 if_cleanup = compiler_new_block(c);
3852 anchor = compiler_new_block(c);
3853
3854 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3855 try == NULL || after_try == NULL ||
3856 except == NULL || after_try == NULL) {
3857 return 0;
3858 }
3859
3860 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3861
3862 if (gen_index == 0) {
3863 /* Receive outermost iter as an implicit argument */
3864 c->u->u_argcount = 1;
3865 ADDOP_I(c, LOAD_FAST, 0);
3866 }
3867 else {
3868 /* Sub-iter - calculate on the fly */
3869 VISIT(c, expr, gen->iter);
3870 ADDOP(c, GET_AITER);
3871 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3872 ADDOP(c, YIELD_FROM);
3873 }
3874
3875 compiler_use_next_block(c, try);
3876
3877
3878 ADDOP_JREL(c, SETUP_EXCEPT, except);
3879 if (!compiler_push_fblock(c, EXCEPT, try))
3880 return 0;
3881
3882 ADDOP(c, GET_ANEXT);
3883 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3884 ADDOP(c, YIELD_FROM);
3885 VISIT(c, expr, gen->target);
3886 ADDOP(c, POP_BLOCK);
3887 compiler_pop_fblock(c, EXCEPT, try);
3888 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3889
3890
3891 compiler_use_next_block(c, except);
3892 ADDOP(c, DUP_TOP);
3893 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3894 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3895 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3896
3897 ADDOP(c, POP_TOP);
3898 ADDOP(c, POP_TOP);
3899 ADDOP(c, POP_TOP);
3900 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3901 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3902
3903
3904 compiler_use_next_block(c, try_cleanup);
3905 ADDOP(c, END_FINALLY);
3906
3907 compiler_use_next_block(c, after_try);
3908
3909 n = asdl_seq_LEN(gen->ifs);
3910 for (i = 0; i < n; i++) {
3911 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003912 if (!compiler_jump_if(c, e, if_cleanup, 0))
3913 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003914 NEXT_BLOCK(c);
3915 }
3916
3917 if (++gen_index < asdl_seq_LEN(generators))
3918 if (!compiler_comprehension_generator(c,
3919 generators, gen_index,
3920 elt, val, type))
3921 return 0;
3922
3923 /* only append after the last for generator */
3924 if (gen_index >= asdl_seq_LEN(generators)) {
3925 /* comprehension specific code */
3926 switch (type) {
3927 case COMP_GENEXP:
3928 VISIT(c, expr, elt);
3929 ADDOP(c, YIELD_VALUE);
3930 ADDOP(c, POP_TOP);
3931 break;
3932 case COMP_LISTCOMP:
3933 VISIT(c, expr, elt);
3934 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3935 break;
3936 case COMP_SETCOMP:
3937 VISIT(c, expr, elt);
3938 ADDOP_I(c, SET_ADD, gen_index + 1);
3939 break;
3940 case COMP_DICTCOMP:
3941 /* With 'd[k] = v', v is evaluated before k, so we do
3942 the same. */
3943 VISIT(c, expr, val);
3944 VISIT(c, expr, elt);
3945 ADDOP_I(c, MAP_ADD, gen_index + 1);
3946 break;
3947 default:
3948 return 0;
3949 }
3950
3951 compiler_use_next_block(c, skip);
3952 }
3953 compiler_use_next_block(c, if_cleanup);
3954 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3955 compiler_use_next_block(c, anchor);
3956 ADDOP(c, POP_TOP);
3957
3958 return 1;
3959}
3960
3961static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003962compiler_comprehension(struct compiler *c, expr_ty e, int type,
3963 identifier name, asdl_seq *generators, expr_ty elt,
3964 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003968 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003969 int is_async_function = c->u->u_ste->ste_coroutine;
3970 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003971
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003973
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003974 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3975 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978 }
3979
3980 is_async_generator = c->u->u_ste->ste_coroutine;
3981
3982 if (is_async_generator && !is_async_function) {
3983 if (e->lineno > c->u->u_lineno) {
3984 c->u->u_lineno = e->lineno;
3985 c->u->u_lineno_set = 0;
3986 }
3987 compiler_error(c, "asynchronous comprehension outside of "
3988 "an asynchronous function");
3989 goto error_in_scope;
3990 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 if (type != COMP_GENEXP) {
3993 int op;
3994 switch (type) {
3995 case COMP_LISTCOMP:
3996 op = BUILD_LIST;
3997 break;
3998 case COMP_SETCOMP:
3999 op = BUILD_SET;
4000 break;
4001 case COMP_DICTCOMP:
4002 op = BUILD_MAP;
4003 break;
4004 default:
4005 PyErr_Format(PyExc_SystemError,
4006 "unknown comprehension type %d", type);
4007 goto error_in_scope;
4008 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 ADDOP_I(c, op, 0);
4011 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 if (!compiler_comprehension_generator(c, generators, 0, elt,
4014 val, type))
4015 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (type != COMP_GENEXP) {
4018 ADDOP(c, RETURN_VALUE);
4019 }
4020
4021 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004022 qualname = c->u->u_qualname;
4023 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004025 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 goto error;
4027
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004028 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004030 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 Py_DECREF(co);
4032
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004033 VISIT(c, expr, outermost->iter);
4034
4035 if (outermost->is_async) {
4036 ADDOP(c, GET_AITER);
4037 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4038 ADDOP(c, YIELD_FROM);
4039 } else {
4040 ADDOP(c, GET_ITER);
4041 }
4042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004044
4045 if (is_async_generator && type != COMP_GENEXP) {
4046 ADDOP(c, GET_AWAITABLE);
4047 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4048 ADDOP(c, YIELD_FROM);
4049 }
4050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004052error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004054error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004055 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 Py_XDECREF(co);
4057 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058}
4059
4060static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061compiler_genexp(struct compiler *c, expr_ty e)
4062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 static identifier name;
4064 if (!name) {
4065 name = PyUnicode_FromString("<genexpr>");
4066 if (!name)
4067 return 0;
4068 }
4069 assert(e->kind == GeneratorExp_kind);
4070 return compiler_comprehension(c, e, COMP_GENEXP, name,
4071 e->v.GeneratorExp.generators,
4072 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073}
4074
4075static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004076compiler_listcomp(struct compiler *c, expr_ty e)
4077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 static identifier name;
4079 if (!name) {
4080 name = PyUnicode_FromString("<listcomp>");
4081 if (!name)
4082 return 0;
4083 }
4084 assert(e->kind == ListComp_kind);
4085 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4086 e->v.ListComp.generators,
4087 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004088}
4089
4090static int
4091compiler_setcomp(struct compiler *c, expr_ty e)
4092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 static identifier name;
4094 if (!name) {
4095 name = PyUnicode_FromString("<setcomp>");
4096 if (!name)
4097 return 0;
4098 }
4099 assert(e->kind == SetComp_kind);
4100 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4101 e->v.SetComp.generators,
4102 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004103}
4104
4105
4106static int
4107compiler_dictcomp(struct compiler *c, expr_ty e)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 static identifier name;
4110 if (!name) {
4111 name = PyUnicode_FromString("<dictcomp>");
4112 if (!name)
4113 return 0;
4114 }
4115 assert(e->kind == DictComp_kind);
4116 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4117 e->v.DictComp.generators,
4118 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004119}
4120
4121
4122static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123compiler_visit_keyword(struct compiler *c, keyword_ty k)
4124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 VISIT(c, expr, k->value);
4126 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127}
4128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 whether they are true or false.
4131
4132 Return values: 1 for true, 0 for false, -1 for non-constant.
4133 */
4134
4135static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004136expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004138 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 switch (e->kind) {
4140 case Ellipsis_kind:
4141 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004142 case Constant_kind:
4143 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 case Num_kind:
4145 return PyObject_IsTrue(e->v.Num.n);
4146 case Str_kind:
4147 return PyObject_IsTrue(e->v.Str.s);
4148 case Name_kind:
4149 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004151 if (id && strcmp(id, "__debug__") == 0)
4152 return !c->c_optimize;
4153 return -1;
4154 case NameConstant_kind: {
4155 PyObject *o = e->v.NameConstant.value;
4156 if (o == Py_None)
4157 return 0;
4158 else if (o == Py_True)
4159 return 1;
4160 else if (o == Py_False)
4161 return 0;
4162 }
Stefan Krahf432a322017-08-21 13:09:59 +02004163 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 default:
4165 return -1;
4166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167}
4168
Yury Selivanov75445082015-05-11 22:57:16 -04004169
4170/*
4171 Implements the async with statement.
4172
4173 The semantics outlined in that PEP are as follows:
4174
4175 async with EXPR as VAR:
4176 BLOCK
4177
4178 It is implemented roughly as:
4179
4180 context = EXPR
4181 exit = context.__aexit__ # not calling it
4182 value = await context.__aenter__()
4183 try:
4184 VAR = value # if VAR present in the syntax
4185 BLOCK
4186 finally:
4187 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004188 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004189 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004190 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004191 if not (await exit(*exc)):
4192 raise
4193 */
4194static int
4195compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4196{
4197 basicblock *block, *finally;
4198 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4199
4200 assert(s->kind == AsyncWith_kind);
4201
4202 block = compiler_new_block(c);
4203 finally = compiler_new_block(c);
4204 if (!block || !finally)
4205 return 0;
4206
4207 /* Evaluate EXPR */
4208 VISIT(c, expr, item->context_expr);
4209
4210 ADDOP(c, BEFORE_ASYNC_WITH);
4211 ADDOP(c, GET_AWAITABLE);
4212 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4213 ADDOP(c, YIELD_FROM);
4214
4215 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4216
4217 /* SETUP_ASYNC_WITH pushes a finally block. */
4218 compiler_use_next_block(c, block);
4219 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4220 return 0;
4221 }
4222
4223 if (item->optional_vars) {
4224 VISIT(c, expr, item->optional_vars);
4225 }
4226 else {
4227 /* Discard result from context.__aenter__() */
4228 ADDOP(c, POP_TOP);
4229 }
4230
4231 pos++;
4232 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4233 /* BLOCK code */
4234 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4235 else if (!compiler_async_with(c, s, pos))
4236 return 0;
4237
4238 /* End of try block; start the finally block */
4239 ADDOP(c, POP_BLOCK);
4240 compiler_pop_fblock(c, FINALLY_TRY, block);
4241
4242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4243 compiler_use_next_block(c, finally);
4244 if (!compiler_push_fblock(c, FINALLY_END, finally))
4245 return 0;
4246
4247 /* Finally block starts; context.__exit__ is on the stack under
4248 the exception or return information. Just issue our magic
4249 opcode. */
4250 ADDOP(c, WITH_CLEANUP_START);
4251
4252 ADDOP(c, GET_AWAITABLE);
4253 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4254 ADDOP(c, YIELD_FROM);
4255
4256 ADDOP(c, WITH_CLEANUP_FINISH);
4257
4258 /* Finally block ends. */
4259 ADDOP(c, END_FINALLY);
4260 compiler_pop_fblock(c, FINALLY_END, finally);
4261 return 1;
4262}
4263
4264
Guido van Rossumc2e20742006-02-27 22:32:47 +00004265/*
4266 Implements the with statement from PEP 343.
4267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004269
4270 with EXPR as VAR:
4271 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272
Guido van Rossumc2e20742006-02-27 22:32:47 +00004273 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274
Thomas Wouters477c8d52006-05-27 19:21:47 +00004275 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004276 exit = context.__exit__ # not calling it
4277 value = context.__enter__()
4278 try:
4279 VAR = value # if VAR present in the syntax
4280 BLOCK
4281 finally:
4282 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004283 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004284 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004285 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004286 exit(*exc)
4287 */
4288static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004289compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004290{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004291 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004292 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004293
4294 assert(s->kind == With_kind);
4295
Guido van Rossumc2e20742006-02-27 22:32:47 +00004296 block = compiler_new_block(c);
4297 finally = compiler_new_block(c);
4298 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004299 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004300
Thomas Wouters477c8d52006-05-27 19:21:47 +00004301 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004302 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004303 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004304
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004305 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004306 compiler_use_next_block(c, block);
4307 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004308 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004309 }
4310
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004311 if (item->optional_vars) {
4312 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004313 }
4314 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004316 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004317 }
4318
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004319 pos++;
4320 if (pos == asdl_seq_LEN(s->v.With.items))
4321 /* BLOCK code */
4322 VISIT_SEQ(c, stmt, s->v.With.body)
4323 else if (!compiler_with(c, s, pos))
4324 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004325
4326 /* End of try block; start the finally block */
4327 ADDOP(c, POP_BLOCK);
4328 compiler_pop_fblock(c, FINALLY_TRY, block);
4329
4330 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4331 compiler_use_next_block(c, finally);
4332 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004333 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004334
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004335 /* Finally block starts; context.__exit__ is on the stack under
4336 the exception or return information. Just issue our magic
4337 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004338 ADDOP(c, WITH_CLEANUP_START);
4339 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004340
4341 /* Finally block ends. */
4342 ADDOP(c, END_FINALLY);
4343 compiler_pop_fblock(c, FINALLY_END, finally);
4344 return 1;
4345}
4346
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347static int
4348compiler_visit_expr(struct compiler *c, expr_ty e)
4349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 /* If expr e has a different line number than the last expr/stmt,
4351 set a new line number for the next instruction.
4352 */
4353 if (e->lineno > c->u->u_lineno) {
4354 c->u->u_lineno = e->lineno;
4355 c->u->u_lineno_set = 0;
4356 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004357 /* Updating the column offset is always harmless. */
4358 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 switch (e->kind) {
4360 case BoolOp_kind:
4361 return compiler_boolop(c, e);
4362 case BinOp_kind:
4363 VISIT(c, expr, e->v.BinOp.left);
4364 VISIT(c, expr, e->v.BinOp.right);
4365 ADDOP(c, binop(c, e->v.BinOp.op));
4366 break;
4367 case UnaryOp_kind:
4368 VISIT(c, expr, e->v.UnaryOp.operand);
4369 ADDOP(c, unaryop(e->v.UnaryOp.op));
4370 break;
4371 case Lambda_kind:
4372 return compiler_lambda(c, e);
4373 case IfExp_kind:
4374 return compiler_ifexp(c, e);
4375 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004376 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004378 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 case GeneratorExp_kind:
4380 return compiler_genexp(c, e);
4381 case ListComp_kind:
4382 return compiler_listcomp(c, e);
4383 case SetComp_kind:
4384 return compiler_setcomp(c, e);
4385 case DictComp_kind:
4386 return compiler_dictcomp(c, e);
4387 case Yield_kind:
4388 if (c->u->u_ste->ste_type != FunctionBlock)
4389 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004390 if (e->v.Yield.value) {
4391 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 }
4393 else {
4394 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4395 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004396 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004398 case YieldFrom_kind:
4399 if (c->u->u_ste->ste_type != FunctionBlock)
4400 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004401
4402 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4403 return compiler_error(c, "'yield from' inside async function");
4404
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004405 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004406 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004407 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4408 ADDOP(c, YIELD_FROM);
4409 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004410 case Await_kind:
4411 if (c->u->u_ste->ste_type != FunctionBlock)
4412 return compiler_error(c, "'await' outside function");
4413
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004414 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4415 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004416 return compiler_error(c, "'await' outside async function");
4417
4418 VISIT(c, expr, e->v.Await.value);
4419 ADDOP(c, GET_AWAITABLE);
4420 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4421 ADDOP(c, YIELD_FROM);
4422 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 case Compare_kind:
4424 return compiler_compare(c, e);
4425 case Call_kind:
4426 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004427 case Constant_kind:
4428 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4429 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 case Num_kind:
4431 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4432 break;
4433 case Str_kind:
4434 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4435 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004436 case JoinedStr_kind:
4437 return compiler_joined_str(c, e);
4438 case FormattedValue_kind:
4439 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 case Bytes_kind:
4441 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4442 break;
4443 case Ellipsis_kind:
4444 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4445 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004446 case NameConstant_kind:
4447 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4448 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 /* The following exprs can be assignment targets. */
4450 case Attribute_kind:
4451 if (e->v.Attribute.ctx != AugStore)
4452 VISIT(c, expr, e->v.Attribute.value);
4453 switch (e->v.Attribute.ctx) {
4454 case AugLoad:
4455 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004456 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 case Load:
4458 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4459 break;
4460 case AugStore:
4461 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004462 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 case Store:
4464 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4465 break;
4466 case Del:
4467 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4468 break;
4469 case Param:
4470 default:
4471 PyErr_SetString(PyExc_SystemError,
4472 "param invalid in attribute expression");
4473 return 0;
4474 }
4475 break;
4476 case Subscript_kind:
4477 switch (e->v.Subscript.ctx) {
4478 case AugLoad:
4479 VISIT(c, expr, e->v.Subscript.value);
4480 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4481 break;
4482 case Load:
4483 VISIT(c, expr, e->v.Subscript.value);
4484 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4485 break;
4486 case AugStore:
4487 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4488 break;
4489 case Store:
4490 VISIT(c, expr, e->v.Subscript.value);
4491 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4492 break;
4493 case Del:
4494 VISIT(c, expr, e->v.Subscript.value);
4495 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4496 break;
4497 case Param:
4498 default:
4499 PyErr_SetString(PyExc_SystemError,
4500 "param invalid in subscript expression");
4501 return 0;
4502 }
4503 break;
4504 case Starred_kind:
4505 switch (e->v.Starred.ctx) {
4506 case Store:
4507 /* In all legitimate cases, the Starred node was already replaced
4508 * by compiler_list/compiler_tuple. XXX: is that okay? */
4509 return compiler_error(c,
4510 "starred assignment target must be in a list or tuple");
4511 default:
4512 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004513 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 }
4515 break;
4516 case Name_kind:
4517 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4518 /* child nodes of List and Tuple will have expr_context set */
4519 case List_kind:
4520 return compiler_list(c, e);
4521 case Tuple_kind:
4522 return compiler_tuple(c, e);
4523 }
4524 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004525}
4526
4527static int
4528compiler_augassign(struct compiler *c, stmt_ty s)
4529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 expr_ty e = s->v.AugAssign.target;
4531 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 switch (e->kind) {
4536 case Attribute_kind:
4537 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4538 AugLoad, e->lineno, e->col_offset, c->c_arena);
4539 if (auge == NULL)
4540 return 0;
4541 VISIT(c, expr, auge);
4542 VISIT(c, expr, s->v.AugAssign.value);
4543 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4544 auge->v.Attribute.ctx = AugStore;
4545 VISIT(c, expr, auge);
4546 break;
4547 case Subscript_kind:
4548 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4549 AugLoad, e->lineno, e->col_offset, c->c_arena);
4550 if (auge == NULL)
4551 return 0;
4552 VISIT(c, expr, auge);
4553 VISIT(c, expr, s->v.AugAssign.value);
4554 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4555 auge->v.Subscript.ctx = AugStore;
4556 VISIT(c, expr, auge);
4557 break;
4558 case Name_kind:
4559 if (!compiler_nameop(c, e->v.Name.id, Load))
4560 return 0;
4561 VISIT(c, expr, s->v.AugAssign.value);
4562 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4563 return compiler_nameop(c, e->v.Name.id, Store);
4564 default:
4565 PyErr_Format(PyExc_SystemError,
4566 "invalid node type (%d) for augmented assignment",
4567 e->kind);
4568 return 0;
4569 }
4570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004571}
4572
4573static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004574check_ann_expr(struct compiler *c, expr_ty e)
4575{
4576 VISIT(c, expr, e);
4577 ADDOP(c, POP_TOP);
4578 return 1;
4579}
4580
4581static int
4582check_annotation(struct compiler *c, stmt_ty s)
4583{
4584 /* Annotations are only evaluated in a module or class. */
4585 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4586 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4587 return check_ann_expr(c, s->v.AnnAssign.annotation);
4588 }
4589 return 1;
4590}
4591
4592static int
4593check_ann_slice(struct compiler *c, slice_ty sl)
4594{
4595 switch(sl->kind) {
4596 case Index_kind:
4597 return check_ann_expr(c, sl->v.Index.value);
4598 case Slice_kind:
4599 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4600 return 0;
4601 }
4602 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4603 return 0;
4604 }
4605 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4606 return 0;
4607 }
4608 break;
4609 default:
4610 PyErr_SetString(PyExc_SystemError,
4611 "unexpected slice kind");
4612 return 0;
4613 }
4614 return 1;
4615}
4616
4617static int
4618check_ann_subscr(struct compiler *c, slice_ty sl)
4619{
4620 /* We check that everything in a subscript is defined at runtime. */
4621 Py_ssize_t i, n;
4622
4623 switch (sl->kind) {
4624 case Index_kind:
4625 case Slice_kind:
4626 if (!check_ann_slice(c, sl)) {
4627 return 0;
4628 }
4629 break;
4630 case ExtSlice_kind:
4631 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4632 for (i = 0; i < n; i++) {
4633 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4634 switch (subsl->kind) {
4635 case Index_kind:
4636 case Slice_kind:
4637 if (!check_ann_slice(c, subsl)) {
4638 return 0;
4639 }
4640 break;
4641 case ExtSlice_kind:
4642 default:
4643 PyErr_SetString(PyExc_SystemError,
4644 "extended slice invalid in nested slice");
4645 return 0;
4646 }
4647 }
4648 break;
4649 default:
4650 PyErr_Format(PyExc_SystemError,
4651 "invalid subscript kind %d", sl->kind);
4652 return 0;
4653 }
4654 return 1;
4655}
4656
4657static int
4658compiler_annassign(struct compiler *c, stmt_ty s)
4659{
4660 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004661 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004662
4663 assert(s->kind == AnnAssign_kind);
4664
4665 /* We perform the actual assignment first. */
4666 if (s->v.AnnAssign.value) {
4667 VISIT(c, expr, s->v.AnnAssign.value);
4668 VISIT(c, expr, targ);
4669 }
4670 switch (targ->kind) {
4671 case Name_kind:
4672 /* If we have a simple name in a module or class, store annotation. */
4673 if (s->v.AnnAssign.simple &&
4674 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4675 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004676 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4677 if (!mangled) {
4678 return 0;
4679 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004680 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004681 /* ADDOP_N decrefs its argument */
4682 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004683 }
4684 break;
4685 case Attribute_kind:
4686 if (!s->v.AnnAssign.value &&
4687 !check_ann_expr(c, targ->v.Attribute.value)) {
4688 return 0;
4689 }
4690 break;
4691 case Subscript_kind:
4692 if (!s->v.AnnAssign.value &&
4693 (!check_ann_expr(c, targ->v.Subscript.value) ||
4694 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4695 return 0;
4696 }
4697 break;
4698 default:
4699 PyErr_Format(PyExc_SystemError,
4700 "invalid node type (%d) for annotated assignment",
4701 targ->kind);
4702 return 0;
4703 }
4704 /* Annotation is evaluated last. */
4705 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4706 return 0;
4707 }
4708 return 1;
4709}
4710
4711static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004712compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 struct fblockinfo *f;
4715 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004716 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 "too many statically nested blocks");
4718 return 0;
4719 }
4720 f = &c->u->u_fblock[c->u->u_nfblocks++];
4721 f->fb_type = t;
4722 f->fb_block = b;
4723 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004724}
4725
4726static void
4727compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 struct compiler_unit *u = c->u;
4730 assert(u->u_nfblocks > 0);
4731 u->u_nfblocks--;
4732 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4733 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004734}
4735
Thomas Wouters89f507f2006-12-13 04:49:30 +00004736static int
4737compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 int i;
4739 struct compiler_unit *u = c->u;
4740 for (i = 0; i < u->u_nfblocks; ++i) {
4741 if (u->u_fblock[i].fb_type == LOOP)
4742 return 1;
4743 }
4744 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004745}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004746/* Raises a SyntaxError and returns 0.
4747 If something goes wrong, a different exception may be raised.
4748*/
4749
4750static int
4751compiler_error(struct compiler *c, const char *errstr)
4752{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004753 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004755
Victor Stinner14e461d2013-08-26 22:28:21 +02004756 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 if (!loc) {
4758 Py_INCREF(Py_None);
4759 loc = Py_None;
4760 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004761 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004762 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 if (!u)
4764 goto exit;
4765 v = Py_BuildValue("(zO)", errstr, u);
4766 if (!v)
4767 goto exit;
4768 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004769 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 Py_DECREF(loc);
4771 Py_XDECREF(u);
4772 Py_XDECREF(v);
4773 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774}
4775
4776static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777compiler_handle_subscr(struct compiler *c, const char *kind,
4778 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004782 /* XXX this code is duplicated */
4783 switch (ctx) {
4784 case AugLoad: /* fall through to Load */
4785 case Load: op = BINARY_SUBSCR; break;
4786 case AugStore:/* fall through to Store */
4787 case Store: op = STORE_SUBSCR; break;
4788 case Del: op = DELETE_SUBSCR; break;
4789 case Param:
4790 PyErr_Format(PyExc_SystemError,
4791 "invalid %s kind %d in subscript\n",
4792 kind, ctx);
4793 return 0;
4794 }
4795 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004796 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 }
4798 else if (ctx == AugStore) {
4799 ADDOP(c, ROT_THREE);
4800 }
4801 ADDOP(c, op);
4802 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004803}
4804
4805static int
4806compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 int n = 2;
4809 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 /* only handles the cases where BUILD_SLICE is emitted */
4812 if (s->v.Slice.lower) {
4813 VISIT(c, expr, s->v.Slice.lower);
4814 }
4815 else {
4816 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 if (s->v.Slice.upper) {
4820 VISIT(c, expr, s->v.Slice.upper);
4821 }
4822 else {
4823 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4824 }
4825
4826 if (s->v.Slice.step) {
4827 n++;
4828 VISIT(c, expr, s->v.Slice.step);
4829 }
4830 ADDOP_I(c, BUILD_SLICE, n);
4831 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004832}
4833
4834static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4836 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 switch (s->kind) {
4839 case Slice_kind:
4840 return compiler_slice(c, s, ctx);
4841 case Index_kind:
4842 VISIT(c, expr, s->v.Index.value);
4843 break;
4844 case ExtSlice_kind:
4845 default:
4846 PyErr_SetString(PyExc_SystemError,
4847 "extended slice invalid in nested slice");
4848 return 0;
4849 }
4850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004851}
4852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004853static int
4854compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 char * kindname = NULL;
4857 switch (s->kind) {
4858 case Index_kind:
4859 kindname = "index";
4860 if (ctx != AugStore) {
4861 VISIT(c, expr, s->v.Index.value);
4862 }
4863 break;
4864 case Slice_kind:
4865 kindname = "slice";
4866 if (ctx != AugStore) {
4867 if (!compiler_slice(c, s, ctx))
4868 return 0;
4869 }
4870 break;
4871 case ExtSlice_kind:
4872 kindname = "extended slice";
4873 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004874 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 for (i = 0; i < n; i++) {
4876 slice_ty sub = (slice_ty)asdl_seq_GET(
4877 s->v.ExtSlice.dims, i);
4878 if (!compiler_visit_nested_slice(c, sub, ctx))
4879 return 0;
4880 }
4881 ADDOP_I(c, BUILD_TUPLE, n);
4882 }
4883 break;
4884 default:
4885 PyErr_Format(PyExc_SystemError,
4886 "invalid subscript kind %d", s->kind);
4887 return 0;
4888 }
4889 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004890}
4891
Thomas Wouters89f507f2006-12-13 04:49:30 +00004892/* End of the compiler section, beginning of the assembler section */
4893
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004894/* do depth-first search of basic block graph, starting with block.
4895 post records the block indices in post-order.
4896
4897 XXX must handle implicit jumps from one block to next
4898*/
4899
Thomas Wouters89f507f2006-12-13 04:49:30 +00004900struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 PyObject *a_bytecode; /* string containing bytecode */
4902 int a_offset; /* offset into bytecode */
4903 int a_nblocks; /* number of reachable blocks */
4904 basicblock **a_postorder; /* list of blocks in dfs postorder */
4905 PyObject *a_lnotab; /* string containing lnotab */
4906 int a_lnotab_off; /* offset into lnotab */
4907 int a_lineno; /* last lineno of emitted instruction */
4908 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004909};
4910
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004911static void
4912dfs(struct compiler *c, basicblock *b, struct assembler *a)
4913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 int i;
4915 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 if (b->b_seen)
4918 return;
4919 b->b_seen = 1;
4920 if (b->b_next != NULL)
4921 dfs(c, b->b_next, a);
4922 for (i = 0; i < b->b_iused; i++) {
4923 instr = &b->b_instr[i];
4924 if (instr->i_jrel || instr->i_jabs)
4925 dfs(c, instr->i_target, a);
4926 }
4927 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004928}
4929
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004930static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004931stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4932{
Larry Hastings3a907972013-11-23 14:49:22 -08004933 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 struct instr *instr;
4935 if (b->b_seen || b->b_startdepth >= depth)
4936 return maxdepth;
4937 b->b_seen = 1;
4938 b->b_startdepth = depth;
4939 for (i = 0; i < b->b_iused; i++) {
4940 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004941 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4942 if (effect == PY_INVALID_STACK_EFFECT) {
4943 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4944 Py_FatalError("PyCompile_OpcodeStackEffect()");
4945 }
4946 depth += effect;
4947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 if (depth > maxdepth)
4949 maxdepth = depth;
4950 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4951 if (instr->i_jrel || instr->i_jabs) {
4952 target_depth = depth;
4953 if (instr->i_opcode == FOR_ITER) {
4954 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004955 }
4956 else if (instr->i_opcode == SETUP_FINALLY ||
4957 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 target_depth = depth+3;
4959 if (target_depth > maxdepth)
4960 maxdepth = target_depth;
4961 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004962 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4963 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4964 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 maxdepth = stackdepth_walk(c, instr->i_target,
4966 target_depth, maxdepth);
4967 if (instr->i_opcode == JUMP_ABSOLUTE ||
4968 instr->i_opcode == JUMP_FORWARD) {
4969 goto out; /* remaining code is dead */
4970 }
4971 }
4972 }
4973 if (b->b_next)
4974 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004975out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 b->b_seen = 0;
4977 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978}
4979
4980/* Find the flow path that needs the largest stack. We assume that
4981 * cycles in the flow graph have no net effect on the stack depth.
4982 */
4983static int
4984stackdepth(struct compiler *c)
4985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 basicblock *b, *entryblock;
4987 entryblock = NULL;
4988 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4989 b->b_seen = 0;
4990 b->b_startdepth = INT_MIN;
4991 entryblock = b;
4992 }
4993 if (!entryblock)
4994 return 0;
4995 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004996}
4997
4998static int
4999assemble_init(struct assembler *a, int nblocks, int firstlineno)
5000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 memset(a, 0, sizeof(struct assembler));
5002 a->a_lineno = firstlineno;
5003 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5004 if (!a->a_bytecode)
5005 return 0;
5006 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5007 if (!a->a_lnotab)
5008 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005009 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 PyErr_NoMemory();
5011 return 0;
5012 }
5013 a->a_postorder = (basicblock **)PyObject_Malloc(
5014 sizeof(basicblock *) * nblocks);
5015 if (!a->a_postorder) {
5016 PyErr_NoMemory();
5017 return 0;
5018 }
5019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005020}
5021
5022static void
5023assemble_free(struct assembler *a)
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 Py_XDECREF(a->a_bytecode);
5026 Py_XDECREF(a->a_lnotab);
5027 if (a->a_postorder)
5028 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005029}
5030
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005031static int
5032blocksize(basicblock *b)
5033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 int i;
5035 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005038 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005040}
5041
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005042/* Appends a pair to the end of the line number table, a_lnotab, representing
5043 the instruction's bytecode offset and line number. See
5044 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005045
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005046static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005047assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005050 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005052
Serhiy Storchakaab874002016-09-11 13:48:15 +03005053 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 if(d_bytecode == 0 && d_lineno == 0)
5059 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 if (d_bytecode > 255) {
5062 int j, nbytes, ncodes = d_bytecode / 255;
5063 nbytes = a->a_lnotab_off + 2 * ncodes;
5064 len = PyBytes_GET_SIZE(a->a_lnotab);
5065 if (nbytes >= len) {
5066 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5067 len = nbytes;
5068 else if (len <= INT_MAX / 2)
5069 len *= 2;
5070 else {
5071 PyErr_NoMemory();
5072 return 0;
5073 }
5074 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5075 return 0;
5076 }
5077 lnotab = (unsigned char *)
5078 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5079 for (j = 0; j < ncodes; j++) {
5080 *lnotab++ = 255;
5081 *lnotab++ = 0;
5082 }
5083 d_bytecode -= ncodes * 255;
5084 a->a_lnotab_off += ncodes * 2;
5085 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005086 assert(0 <= d_bytecode && d_bytecode <= 255);
5087
5088 if (d_lineno < -128 || 127 < d_lineno) {
5089 int j, nbytes, ncodes, k;
5090 if (d_lineno < 0) {
5091 k = -128;
5092 /* use division on positive numbers */
5093 ncodes = (-d_lineno) / 128;
5094 }
5095 else {
5096 k = 127;
5097 ncodes = d_lineno / 127;
5098 }
5099 d_lineno -= ncodes * k;
5100 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 nbytes = a->a_lnotab_off + 2 * ncodes;
5102 len = PyBytes_GET_SIZE(a->a_lnotab);
5103 if (nbytes >= len) {
5104 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5105 len = nbytes;
5106 else if (len <= INT_MAX / 2)
5107 len *= 2;
5108 else {
5109 PyErr_NoMemory();
5110 return 0;
5111 }
5112 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5113 return 0;
5114 }
5115 lnotab = (unsigned char *)
5116 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5117 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005118 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 d_bytecode = 0;
5120 for (j = 1; j < ncodes; j++) {
5121 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005122 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 a->a_lnotab_off += ncodes * 2;
5125 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005126 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 len = PyBytes_GET_SIZE(a->a_lnotab);
5129 if (a->a_lnotab_off + 2 >= len) {
5130 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5131 return 0;
5132 }
5133 lnotab = (unsigned char *)
5134 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 a->a_lnotab_off += 2;
5137 if (d_bytecode) {
5138 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005139 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 }
5141 else { /* First line of a block; def stmt, etc. */
5142 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005143 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 }
5145 a->a_lineno = i->i_lineno;
5146 a->a_lineno_off = a->a_offset;
5147 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005148}
5149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005150/* assemble_emit()
5151 Extend the bytecode with a new instruction.
5152 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005153*/
5154
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005155static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005156assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005157{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005158 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005160 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005161
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005162 arg = i->i_oparg;
5163 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (i->i_lineno && !assemble_lnotab(a, i))
5165 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005166 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 if (len > PY_SSIZE_T_MAX / 2)
5168 return 0;
5169 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5170 return 0;
5171 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005172 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005174 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005176}
5177
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005178static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005179assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005182 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 /* Compute the size of each block and fixup jump args.
5186 Replace block pointer with position in bytecode. */
5187 do {
5188 totsize = 0;
5189 for (i = a->a_nblocks - 1; i >= 0; i--) {
5190 b = a->a_postorder[i];
5191 bsize = blocksize(b);
5192 b->b_offset = totsize;
5193 totsize += bsize;
5194 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005195 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5197 bsize = b->b_offset;
5198 for (i = 0; i < b->b_iused; i++) {
5199 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005200 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 /* Relative jumps are computed relative to
5202 the instruction pointer after fetching
5203 the jump instruction.
5204 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005205 bsize += isize;
5206 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005208 if (instr->i_jrel) {
5209 instr->i_oparg -= bsize;
5210 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005211 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005212 if (instrsize(instr->i_oparg) != isize) {
5213 extended_arg_recompile = 1;
5214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 }
5217 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 /* XXX: This is an awful hack that could hurt performance, but
5220 on the bright side it should work until we come up
5221 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 The issue is that in the first loop blocksize() is called
5224 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005225 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 So we loop until we stop seeing new EXTENDED_ARGs.
5229 The only EXTENDED_ARGs that could be popping up are
5230 ones in jump instructions. So this should converge
5231 fairly quickly.
5232 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005233 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005234}
5235
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005236static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005237dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005240 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 tuple = PyTuple_New(size);
5243 if (tuple == NULL)
5244 return NULL;
5245 while (PyDict_Next(dict, &pos, &k, &v)) {
5246 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005247 /* The keys of the dictionary are tuples. (see compiler_add_o
5248 * and _PyCode_ConstantKey). The object we want is always second,
5249 * though. */
5250 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 Py_INCREF(k);
5252 assert((i - offset) < size);
5253 assert((i - offset) >= 0);
5254 PyTuple_SET_ITEM(tuple, i - offset, k);
5255 }
5256 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005257}
5258
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005259static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005260compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005263 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005265 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 if (ste->ste_nested)
5267 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005268 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005270 if (!ste->ste_generator && ste->ste_coroutine)
5271 flags |= CO_COROUTINE;
5272 if (ste->ste_generator && ste->ste_coroutine)
5273 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 if (ste->ste_varargs)
5275 flags |= CO_VARARGS;
5276 if (ste->ste_varkeywords)
5277 flags |= CO_VARKEYWORDS;
5278 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 /* (Only) inherit compilerflags in PyCF_MASK */
5281 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005282
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005283 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5284 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5285 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005289}
5290
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005291static PyCodeObject *
5292makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 PyObject *tmp;
5295 PyCodeObject *co = NULL;
5296 PyObject *consts = NULL;
5297 PyObject *names = NULL;
5298 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 PyObject *name = NULL;
5300 PyObject *freevars = NULL;
5301 PyObject *cellvars = NULL;
5302 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005303 Py_ssize_t nlocals;
5304 int nlocals_int;
5305 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005306 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 tmp = dict_keys_inorder(c->u->u_consts, 0);
5309 if (!tmp)
5310 goto error;
5311 consts = PySequence_List(tmp); /* optimize_code requires a list */
5312 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 names = dict_keys_inorder(c->u->u_names, 0);
5315 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5316 if (!consts || !names || !varnames)
5317 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5320 if (!cellvars)
5321 goto error;
5322 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5323 if (!freevars)
5324 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005325
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005326 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005327 assert(nlocals < INT_MAX);
5328 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 flags = compute_code_flags(c);
5331 if (flags < 0)
5332 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5335 if (!bytecode)
5336 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5339 if (!tmp)
5340 goto error;
5341 Py_DECREF(consts);
5342 consts = tmp;
5343
Victor Stinnerf8e32212013-11-19 23:56:34 +01005344 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5345 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5346 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005347 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 bytecode, consts, names, varnames,
5349 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005350 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 c->u->u_firstlineno,
5352 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005353 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 Py_XDECREF(consts);
5355 Py_XDECREF(names);
5356 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 Py_XDECREF(name);
5358 Py_XDECREF(freevars);
5359 Py_XDECREF(cellvars);
5360 Py_XDECREF(bytecode);
5361 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005362}
5363
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005364
5365/* For debugging purposes only */
5366#if 0
5367static void
5368dump_instr(const struct instr *i)
5369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 const char *jrel = i->i_jrel ? "jrel " : "";
5371 const char *jabs = i->i_jabs ? "jabs " : "";
5372 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005375 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5379 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005380}
5381
5382static void
5383dump_basicblock(const basicblock *b)
5384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 const char *seen = b->b_seen ? "seen " : "";
5386 const char *b_return = b->b_return ? "return " : "";
5387 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5388 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5389 if (b->b_instr) {
5390 int i;
5391 for (i = 0; i < b->b_iused; i++) {
5392 fprintf(stderr, " [%02d] ", i);
5393 dump_instr(b->b_instr + i);
5394 }
5395 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005396}
5397#endif
5398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005399static PyCodeObject *
5400assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 basicblock *b, *entryblock;
5403 struct assembler a;
5404 int i, j, nblocks;
5405 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 /* Make sure every block that falls off the end returns None.
5408 XXX NEXT_BLOCK() isn't quite right, because if the last
5409 block ends with a jump or return b_next shouldn't set.
5410 */
5411 if (!c->u->u_curblock->b_return) {
5412 NEXT_BLOCK(c);
5413 if (addNone)
5414 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5415 ADDOP(c, RETURN_VALUE);
5416 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 nblocks = 0;
5419 entryblock = NULL;
5420 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5421 nblocks++;
5422 entryblock = b;
5423 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 /* Set firstlineno if it wasn't explicitly set. */
5426 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005427 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5429 else
5430 c->u->u_firstlineno = 1;
5431 }
5432 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5433 goto error;
5434 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 /* Can't modify the bytecode after computing jump offsets. */
5437 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 /* Emit code in reverse postorder from dfs. */
5440 for (i = a.a_nblocks - 1; i >= 0; i--) {
5441 b = a.a_postorder[i];
5442 for (j = 0; j < b->b_iused; j++)
5443 if (!assemble_emit(&a, &b->b_instr[j]))
5444 goto error;
5445 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5448 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005449 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 assemble_free(&a);
5455 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005456}
Georg Brandl8334fd92010-12-04 10:26:46 +00005457
5458#undef PyAST_Compile
5459PyAPI_FUNC(PyCodeObject *)
5460PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5461 PyArena *arena)
5462{
5463 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5464}