blob: df5070aad2aef7675c84f6e786c0d7a226366866 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (c.c_st == NULL) {
336 if (!PyErr_Occurred())
337 PyErr_SetString(PyExc_SystemError, "no symtable");
338 goto finally;
339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Thomas Wouters1175c432006-02-27 22:49:54 +0000343 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 compiler_free(&c);
345 assert(co || PyErr_Occurred());
346 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347}
348
349PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200350PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
351 int optimize, PyArena *arena)
352{
353 PyObject *filename;
354 PyCodeObject *co;
355 filename = PyUnicode_DecodeFSDefault(filename_str);
356 if (filename == NULL)
357 return NULL;
358 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
359 Py_DECREF(filename);
360 return co;
361
362}
363
364PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365PyNode_Compile(struct _node *n, const char *filename)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyCodeObject *co = NULL;
368 mod_ty mod;
369 PyArena *arena = PyArena_New();
370 if (!arena)
371 return NULL;
372 mod = PyAST_FromNode(n, NULL, filename, arena);
373 if (mod)
374 co = PyAST_Compile(mod, filename, NULL, arena);
375 PyArena_Free(arena);
376 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000377}
378
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (c->c_st)
383 PySymtable_Free(c->c_st);
384 if (c->c_future)
385 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000388}
389
Guido van Rossum79f25d91997-04-29 20:08:16 +0000390static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t i, n;
394 PyObject *v, *k;
395 PyObject *dict = PyDict_New();
396 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 n = PyList_Size(list);
399 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100400 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (!v) {
402 Py_DECREF(dict);
403 return NULL;
404 }
405 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100406 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
408 Py_XDECREF(k);
409 Py_DECREF(v);
410 Py_DECREF(dict);
411 return NULL;
412 }
413 Py_DECREF(k);
414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100462 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100469 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
474 Py_XDECREF(tuple);
475 return NULL;
476 }
477 Py_DECREF(item);
478 Py_DECREF(tuple);
479 }
480 }
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000483}
484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485static void
486compiler_unit_check(struct compiler_unit *u)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 basicblock *block;
489 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700490 assert((uintptr_t)block != 0xcbcbcbcbU);
491 assert((uintptr_t)block != 0xfbfbfbfbU);
492 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (block->b_instr != NULL) {
494 assert(block->b_ialloc > 0);
495 assert(block->b_iused > 0);
496 assert(block->b_ialloc >= block->b_iused);
497 }
498 else {
499 assert (block->b_iused == 0);
500 assert (block->b_ialloc == 0);
501 }
502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503}
504
505static void
506compiler_unit_free(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 compiler_unit_check(u);
511 b = u->u_blocks;
512 while (b != NULL) {
513 if (b->b_instr)
514 PyObject_Free((void *)b->b_instr);
515 next = b->b_list;
516 PyObject_Free((void *)b);
517 b = next;
518 }
519 Py_CLEAR(u->u_ste);
520 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400521 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_CLEAR(u->u_consts);
523 Py_CLEAR(u->u_names);
524 Py_CLEAR(u->u_varnames);
525 Py_CLEAR(u->u_freevars);
526 Py_CLEAR(u->u_cellvars);
527 Py_CLEAR(u->u_private);
528 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100532compiler_enter_scope(struct compiler *c, identifier name,
533 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100536 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
539 struct compiler_unit));
540 if (!u) {
541 PyErr_NoMemory();
542 return 0;
543 }
544 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100545 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_argcount = 0;
547 u->u_kwonlyargcount = 0;
548 u->u_ste = PySymtable_Lookup(c->c_st, key);
549 if (!u->u_ste) {
550 compiler_unit_free(u);
551 return 0;
552 }
553 Py_INCREF(name);
554 u->u_name = name;
555 u->u_varnames = list2dict(u->u_ste->ste_varnames);
556 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
557 if (!u->u_varnames || !u->u_cellvars) {
558 compiler_unit_free(u);
559 return 0;
560 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000562 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300564 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 int res;
566 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200567 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 name = _PyUnicode_FromId(&PyId___class__);
569 if (!name) {
570 compiler_unit_free(u);
571 return 0;
572 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100573 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 if (!tuple) {
575 compiler_unit_free(u);
576 return 0;
577 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300578 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (res < 0) {
581 compiler_unit_free(u);
582 return 0;
583 }
584 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200587 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (!u->u_freevars) {
589 compiler_unit_free(u);
590 return 0;
591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_blocks = NULL;
594 u->u_nfblocks = 0;
595 u->u_firstlineno = lineno;
596 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000597 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 u->u_lineno_set = 0;
599 u->u_consts = PyDict_New();
600 if (!u->u_consts) {
601 compiler_unit_free(u);
602 return 0;
603 }
604 u->u_names = PyDict_New();
605 if (!u->u_names) {
606 compiler_unit_free(u);
607 return 0;
608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Push the old compiler_unit on the stack. */
613 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400614 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
616 Py_XDECREF(capsule);
617 compiler_unit_free(u);
618 return 0;
619 }
620 Py_DECREF(capsule);
621 u->u_private = c->u->u_private;
622 Py_XINCREF(u->u_private);
623 }
624 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627
628 block = compiler_new_block(c);
629 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400633 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
634 if (!compiler_set_qualname(c))
635 return 0;
636 }
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642compiler_exit_scope(struct compiler *c)
643{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100644 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel--;
648 compiler_unit_free(c->u);
649 /* Restore c->u to the parent unit. */
650 n = PyList_GET_SIZE(c->c_stack) - 1;
651 if (n >= 0) {
652 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400653 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(c->u);
655 /* we are deleting from a list so this really shouldn't fail */
656 if (PySequence_DelItem(c->c_stack, n) < 0)
657 Py_FatalError("compiler_exit_scope()");
658 compiler_unit_check(c->u);
659 }
660 else
661 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663}
664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665static int
666compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 _Py_static_string(dot_locals, ".<locals>");
670 Py_ssize_t stack_size;
671 struct compiler_unit *u = c->u;
672 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400676 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 if (stack_size > 1) {
678 int scope, force_global = 0;
679 struct compiler_unit *parent;
680 PyObject *mangled, *capsule;
681
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400682 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 assert(parent);
685
Yury Selivanov75445082015-05-11 22:57:16 -0400686 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
687 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 assert(u->u_name);
690 mangled = _Py_Mangle(parent->u_private, u->u_name);
691 if (!mangled)
692 return 0;
693 scope = PyST_GetScope(parent->u_ste, mangled);
694 Py_DECREF(mangled);
695 assert(scope != GLOBAL_IMPLICIT);
696 if (scope == GLOBAL_EXPLICIT)
697 force_global = 1;
698 }
699
700 if (!force_global) {
701 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400702 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
704 dot_locals_str = _PyUnicode_FromId(&dot_locals);
705 if (dot_locals_str == NULL)
706 return 0;
707 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
708 if (base == NULL)
709 return 0;
710 }
711 else {
712 Py_INCREF(parent->u_qualname);
713 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100715 }
716 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400717
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 if (base != NULL) {
719 dot_str = _PyUnicode_FromId(&dot);
720 if (dot_str == NULL) {
721 Py_DECREF(base);
722 return 0;
723 }
724 name = PyUnicode_Concat(base, dot_str);
725 Py_DECREF(base);
726 if (name == NULL)
727 return 0;
728 PyUnicode_Append(&name, u->u_name);
729 if (name == NULL)
730 return 0;
731 }
732 else {
733 Py_INCREF(u->u_name);
734 name = u->u_name;
735 }
736 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739}
740
Eric V. Smith235a6f02015-09-19 14:51:32 -0400741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742/* Allocate a new block and return a pointer to it.
743 Returns NULL on error.
744*/
745
746static basicblock *
747compiler_new_block(struct compiler *c)
748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 basicblock *b;
750 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 u = c->u;
753 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
754 if (b == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 memset((void *)b, 0, sizeof(basicblock));
759 /* Extend the singly linked list of blocks with new block. */
760 b->b_list = u->u_blocks;
761 u->u_blocks = b;
762 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700811 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
Larry Hastings3a907972013-11-23 14:49:22 -0800856int
857PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400884 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_MODULO:
886 case BINARY_ADD:
887 case BINARY_SUBTRACT:
888 case BINARY_SUBSCR:
889 case BINARY_FLOOR_DIVIDE:
890 case BINARY_TRUE_DIVIDE:
891 return -1;
892 case INPLACE_FLOOR_DIVIDE:
893 case INPLACE_TRUE_DIVIDE:
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_ADD:
897 case INPLACE_SUBTRACT:
898 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400899 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_MODULO:
901 return -1;
902 case STORE_SUBSCR:
903 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400932 case WITH_CLEANUP_START:
933 return 1;
934 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case RETURN_VALUE:
937 return -1;
938 case IMPORT_STAR:
939 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700940 case SETUP_ANNOTATIONS:
941 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300979 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300983 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400984 case BUILD_SET_UNPACK:
985 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400986 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700987 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300990 case BUILD_CONST_KEY_MAP:
991 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case LOAD_ATTR:
993 return 0;
994 case COMPARE_OP:
995 return -1;
996 case IMPORT_NAME:
997 return -1;
998 case IMPORT_FROM:
999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case JUMP_FORWARD:
1002 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1003 case JUMP_IF_FALSE_OR_POP: /* "" */
1004 case JUMP_ABSOLUTE:
1005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case POP_JUMP_IF_FALSE:
1008 case POP_JUMP_IF_TRUE:
1009 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_GLOBAL:
1012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case CONTINUE_LOOP:
1015 return 0;
1016 case SETUP_LOOP:
1017 return 0;
1018 case SETUP_EXCEPT:
1019 case SETUP_FINALLY:
1020 return 6; /* can push 3 values for the new exception
1021 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case LOAD_FAST:
1024 return 1;
1025 case STORE_FAST:
1026 return -1;
1027 case DELETE_FAST:
1028 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001029 case STORE_ANNOTATION:
1030 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case RAISE_VARARGS:
1033 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001035 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001036 case CALL_METHOD:
1037 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg-1;
1040 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001041 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001042 case MAKE_FUNCTION:
1043 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1044 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case BUILD_SLICE:
1046 if (oparg == 3)
1047 return -2;
1048 else
1049 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case LOAD_CLOSURE:
1052 return 1;
1053 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001054 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 1;
1056 case STORE_DEREF:
1057 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001058 case DELETE_DEREF:
1059 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001060 case GET_AWAITABLE:
1061 return 0;
1062 case SETUP_ASYNC_WITH:
1063 return 6;
1064 case BEFORE_ASYNC_WITH:
1065 return 1;
1066 case GET_AITER:
1067 return 0;
1068 case GET_ANEXT:
1069 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001070 case GET_YIELD_FROM_ITER:
1071 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001072 case FORMAT_VALUE:
1073 /* If there's a fmt_spec on the stack, we go from 2->1,
1074 else 1->1. */
1075 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001076 case LOAD_METHOD:
1077 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001079 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Larry Hastings3a907972013-11-23 14:49:22 -08001081 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082}
1083
1084/* Add an opcode with no argument.
1085 Returns 0 on failure, 1 on success.
1086*/
1087
1088static int
1089compiler_addop(struct compiler *c, int opcode)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 basicblock *b;
1092 struct instr *i;
1093 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001094 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 off = compiler_next_instr(c, c->u->u_curblock);
1096 if (off < 0)
1097 return 0;
1098 b = c->u->u_curblock;
1099 i = &b->b_instr[off];
1100 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (opcode == RETURN_VALUE)
1103 b->b_return = 1;
1104 compiler_set_lineno(c, off);
1105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106}
1107
Victor Stinnerf8e32212013-11-19 23:56:34 +01001108static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *t, *v;
1112 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Victor Stinnerefb24132016-01-22 12:33:12 +01001114 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (t == NULL)
1116 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 v = PyDict_GetItem(dict, t);
1119 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001120 if (PyErr_Occurred()) {
1121 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001123 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001124 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001125 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!v) {
1127 Py_DECREF(t);
1128 return -1;
1129 }
1130 if (PyDict_SetItem(dict, t, v) < 0) {
1131 Py_DECREF(t);
1132 Py_DECREF(v);
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 }
1137 else
1138 arg = PyLong_AsLong(v);
1139 Py_DECREF(t);
1140 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
1143static int
1144compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001149 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return compiler_addop_i(c, opcode, arg);
1151}
1152
1153static int
1154compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001157 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1159 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 arg = compiler_add_o(c, dict, mangled);
1162 Py_DECREF(mangled);
1163 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return compiler_addop_i(c, opcode, arg);
1166}
1167
1168/* Add an opcode with an integer argument.
1169 Returns 0 on failure, 1 on success.
1170*/
1171
1172static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 struct instr *i;
1176 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Victor Stinner2ad474b2016-03-01 23:34:47 +01001178 /* oparg value is unsigned, but a signed C int is usually used to store
1179 it in the C code (like Python/ceval.c).
1180
1181 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1182
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 The argument of a concrete bytecode instruction is limited to 8-bit.
1184 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1185 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001186 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 off = compiler_next_instr(c, c->u->u_curblock);
1189 if (off < 0)
1190 return 0;
1191 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001192 i->i_opcode = opcode;
1193 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001204 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 assert(b != NULL);
1206 off = compiler_next_instr(c, c->u->u_curblock);
1207 if (off < 0)
1208 return 0;
1209 i = &c->u->u_curblock->b_instr[off];
1210 i->i_opcode = opcode;
1211 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001220/* NEXT_BLOCK() creates an implicit jump from the current block
1221 to the new block.
1222
1223 The returns inside this macro make it impossible to decref objects
1224 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (compiler_next_block((C)) == NULL) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop((C), (OP))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001236#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop((C), (OP))) { \
1238 compiler_exit_scope(c); \
1239 return 0; \
1240 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001241}
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001248/* Same as ADDOP_O, but steals a reference. */
1249#define ADDOP_N(C, OP, O, TYPE) { \
1250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1251 Py_DECREF((O)); \
1252 return 0; \
1253 } \
1254 Py_DECREF((O)); \
1255}
1256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_i((C), (OP), (O))) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop_j((C), (OP), (O), 1)) \
1269 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
1272#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_addop_j((C), (OP), (O), 0)) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
1277/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1278 the ASDL name to synthesize the name of the C type and the visit function.
1279*/
1280
1281#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_visit_ ## TYPE((C), (V))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_visit_ ## TYPE((C), (V))) { \
1288 compiler_exit_scope(c); \
1289 return 0; \
1290 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001291}
1292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_slice((C), (V), (CTX))) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 int _i; \
1300 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1301 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1302 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1303 if (!compiler_visit_ ## TYPE((C), elt)) \
1304 return 0; \
1305 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 int _i; \
1310 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1311 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1312 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1313 if (!compiler_visit_ ## TYPE((C), elt)) { \
1314 compiler_exit_scope(c); \
1315 return 0; \
1316 } \
1317 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001318}
1319
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001321is_const(expr_ty e)
1322{
1323 switch (e->kind) {
1324 case Constant_kind:
1325 case Num_kind:
1326 case Str_kind:
1327 case Bytes_kind:
1328 case Ellipsis_kind:
1329 case NameConstant_kind:
1330 return 1;
1331 default:
1332 return 0;
1333 }
1334}
1335
1336static PyObject *
1337get_const_value(expr_ty e)
1338{
1339 switch (e->kind) {
1340 case Constant_kind:
1341 return e->v.Constant.value;
1342 case Num_kind:
1343 return e->v.Num.n;
1344 case Str_kind:
1345 return e->v.Str.s;
1346 case Bytes_kind:
1347 return e->v.Bytes.s;
1348 case Ellipsis_kind:
1349 return Py_Ellipsis;
1350 case NameConstant_kind:
1351 return e->v.NameConstant.value;
1352 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001353 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001354 }
1355}
1356
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001357/* Search if variable annotations are present statically in a block. */
1358
1359static int
1360find_ann(asdl_seq *stmts)
1361{
1362 int i, j, res = 0;
1363 stmt_ty st;
1364
1365 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1366 st = (stmt_ty)asdl_seq_GET(stmts, i);
1367 switch (st->kind) {
1368 case AnnAssign_kind:
1369 return 1;
1370 case For_kind:
1371 res = find_ann(st->v.For.body) ||
1372 find_ann(st->v.For.orelse);
1373 break;
1374 case AsyncFor_kind:
1375 res = find_ann(st->v.AsyncFor.body) ||
1376 find_ann(st->v.AsyncFor.orelse);
1377 break;
1378 case While_kind:
1379 res = find_ann(st->v.While.body) ||
1380 find_ann(st->v.While.orelse);
1381 break;
1382 case If_kind:
1383 res = find_ann(st->v.If.body) ||
1384 find_ann(st->v.If.orelse);
1385 break;
1386 case With_kind:
1387 res = find_ann(st->v.With.body);
1388 break;
1389 case AsyncWith_kind:
1390 res = find_ann(st->v.AsyncWith.body);
1391 break;
1392 case Try_kind:
1393 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1394 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1395 st->v.Try.handlers, j);
1396 if (find_ann(handler->v.ExceptHandler.body)) {
1397 return 1;
1398 }
1399 }
1400 res = find_ann(st->v.Try.body) ||
1401 find_ann(st->v.Try.finalbody) ||
1402 find_ann(st->v.Try.orelse);
1403 break;
1404 default:
1405 res = 0;
1406 }
1407 if (res) {
1408 break;
1409 }
1410 }
1411 return res;
1412}
1413
1414/* Compile a sequence of statements, checking for a docstring
1415 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416
1417static int
INADA Naokicb41b272017-02-23 00:31:59 +09001418compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001420 /* Set current line number to the line number of first statement.
1421 This way line number for SETUP_ANNOTATIONS will always
1422 coincide with the line number of first "real" statement in module.
1423 If body is empy, then lineno will be set later in assemble. */
1424 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1425 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001426 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001427 c->u->u_lineno = st->lineno;
1428 }
1429 /* Every annotated class and module should have __annotations__. */
1430 if (find_ann(stmts)) {
1431 ADDOP(c, SETUP_ANNOTATIONS);
1432 }
INADA Naokicb41b272017-02-23 00:31:59 +09001433 /* if not -OO mode, set docstring */
1434 if (c->c_optimize < 2 && docstring) {
1435 ADDOP_O(c, LOAD_CONST, docstring, consts);
1436 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 }
INADA Naokicb41b272017-02-23 00:31:59 +09001438 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442static PyCodeObject *
1443compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyCodeObject *co;
1446 int addNone = 1;
1447 static PyObject *module;
1448 if (!module) {
1449 module = PyUnicode_InternFromString("<module>");
1450 if (!module)
1451 return NULL;
1452 }
1453 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001454 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 return NULL;
1456 switch (mod->kind) {
1457 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001458 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 compiler_exit_scope(c);
1460 return 0;
1461 }
1462 break;
1463 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001464 if (find_ann(mod->v.Interactive.body)) {
1465 ADDOP(c, SETUP_ANNOTATIONS);
1466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 c->c_interactive = 1;
1468 VISIT_SEQ_IN_SCOPE(c, stmt,
1469 mod->v.Interactive.body);
1470 break;
1471 case Expression_kind:
1472 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1473 addNone = 0;
1474 break;
1475 case Suite_kind:
1476 PyErr_SetString(PyExc_SystemError,
1477 "suite should not be possible");
1478 return 0;
1479 default:
1480 PyErr_Format(PyExc_SystemError,
1481 "module kind %d should not be possible",
1482 mod->kind);
1483 return 0;
1484 }
1485 co = assemble(c, addNone);
1486 compiler_exit_scope(c);
1487 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490/* The test for LOCAL must come before the test for FREE in order to
1491 handle classes where name is both local and free. The local var is
1492 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001493*/
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495static int
1496get_ref_type(struct compiler *c, PyObject *name)
1497{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001498 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001499 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001500 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001501 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001502 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (scope == 0) {
1504 char buf[350];
1505 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001506 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001508 PyUnicode_AsUTF8(name),
1509 PyUnicode_AsUTF8(c->u->u_name),
1510 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1511 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1512 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1513 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 );
1515 Py_FatalError(buf);
1516 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
1521static int
1522compiler_lookup_arg(PyObject *dict, PyObject *name)
1523{
1524 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001525 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001527 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001529 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001531 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001532 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
1535static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001536compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001538 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001539 if (qualname == NULL)
1540 qualname = co->co_name;
1541
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001542 if (free) {
1543 for (i = 0; i < free; ++i) {
1544 /* Bypass com_addop_varname because it will generate
1545 LOAD_DEREF but LOAD_CLOSURE is needed.
1546 */
1547 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1548 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001549
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001550 /* Special case: If a class contains a method with a
1551 free variable that has the same name as a method,
1552 the name will be considered free *and* local in the
1553 class. It should be handled by the closure, as
1554 well as by the normal name loookup logic.
1555 */
1556 reftype = get_ref_type(c, name);
1557 if (reftype == CELL)
1558 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1559 else /* (reftype == FREE) */
1560 arg = compiler_lookup_arg(c->u->u_freevars, name);
1561 if (arg == -1) {
1562 fprintf(stderr,
1563 "lookup %s in %s %d %d\n"
1564 "freevars of %s: %s\n",
1565 PyUnicode_AsUTF8(PyObject_Repr(name)),
1566 PyUnicode_AsUTF8(c->u->u_name),
1567 reftype, arg,
1568 PyUnicode_AsUTF8(co->co_name),
1569 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1570 Py_FatalError("compiler_make_closure()");
1571 }
1572 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001574 flags |= 0x08;
1575 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001578 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001579 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581}
1582
1583static int
1584compiler_decorators(struct compiler *c, asdl_seq* decos)
1585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (!decos)
1589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1592 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1593 }
1594 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595}
1596
1597static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001598compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001600{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001601 /* Push a dict of keyword-only default values.
1602
1603 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1604 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001605 int i;
1606 PyObject *keys = NULL;
1607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1609 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1610 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1611 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001612 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001613 if (!mangled) {
1614 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001616 if (keys == NULL) {
1617 keys = PyList_New(1);
1618 if (keys == NULL) {
1619 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001620 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001621 }
1622 PyList_SET_ITEM(keys, 0, mangled);
1623 }
1624 else {
1625 int res = PyList_Append(keys, mangled);
1626 Py_DECREF(mangled);
1627 if (res == -1) {
1628 goto error;
1629 }
1630 }
1631 if (!compiler_visit_expr(c, default_)) {
1632 goto error;
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 }
1635 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001636 if (keys != NULL) {
1637 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1638 PyObject *keys_tuple = PyList_AsTuple(keys);
1639 Py_DECREF(keys);
1640 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001641 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001642 }
1643 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1644 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001645 assert(default_count > 0);
1646 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001647 }
1648 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001649 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001650 }
1651
1652error:
1653 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001654 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001655}
1656
1657static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001658compiler_visit_argannotation(struct compiler *c, identifier id,
1659 expr_ty annotation, PyObject *names)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001662 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001664 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001665 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001666 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001667 if (PyList_Append(names, mangled) < 0) {
1668 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001669 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001670 }
1671 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001673 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001674}
1675
1676static int
1677compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1678 PyObject *names)
1679{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001680 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 for (i = 0; i < asdl_seq_LEN(args); i++) {
1682 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001683 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 c,
1685 arg->arg,
1686 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001687 names))
1688 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001690 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001691}
1692
1693static int
1694compiler_visit_annotations(struct compiler *c, arguments_ty args,
1695 expr_ty returns)
1696{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001697 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001698 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001699
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001700 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 */
1702 static identifier return_str;
1703 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001704 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 names = PyList_New(0);
1706 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001707 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001708
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001709 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001711 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001712 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001713 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001715 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001717 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001718 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001719 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (!return_str) {
1723 return_str = PyUnicode_InternFromString("return");
1724 if (!return_str)
1725 goto error;
1726 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001727 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 goto error;
1729 }
1730
1731 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001733 PyObject *keytuple = PyList_AsTuple(names);
1734 Py_DECREF(names);
1735 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001736 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001738 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1739 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001740 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001742 else {
1743 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001744 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001745 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001746
1747error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001749 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001750}
1751
1752static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001753compiler_visit_defaults(struct compiler *c, arguments_ty args)
1754{
1755 VISIT_SEQ(c, expr, args->defaults);
1756 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758}
1759
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001760static Py_ssize_t
1761compiler_default_arguments(struct compiler *c, arguments_ty args)
1762{
1763 Py_ssize_t funcflags = 0;
1764 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 if (!compiler_visit_defaults(c, args))
1766 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001767 funcflags |= 0x01;
1768 }
1769 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001770 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001771 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001772 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001773 return -1;
1774 }
1775 else if (res > 0) {
1776 funcflags |= 0x02;
1777 }
1778 }
1779 return funcflags;
1780}
1781
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782static int
Yury Selivanov75445082015-05-11 22:57:16 -04001783compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001786 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001787 arguments_ty args;
1788 expr_ty returns;
1789 identifier name;
1790 asdl_seq* decos;
1791 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001792 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001793 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001794 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795
Yury Selivanov75445082015-05-11 22:57:16 -04001796 if (is_async) {
1797 assert(s->kind == AsyncFunctionDef_kind);
1798
1799 args = s->v.AsyncFunctionDef.args;
1800 returns = s->v.AsyncFunctionDef.returns;
1801 decos = s->v.AsyncFunctionDef.decorator_list;
1802 name = s->v.AsyncFunctionDef.name;
1803 body = s->v.AsyncFunctionDef.body;
1804
1805 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1806 } else {
1807 assert(s->kind == FunctionDef_kind);
1808
1809 args = s->v.FunctionDef.args;
1810 returns = s->v.FunctionDef.returns;
1811 decos = s->v.FunctionDef.decorator_list;
1812 name = s->v.FunctionDef.name;
1813 body = s->v.FunctionDef.body;
1814
1815 scope_type = COMPILER_SCOPE_FUNCTION;
1816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (!compiler_decorators(c, decos))
1819 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001820
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001821 funcflags = compiler_default_arguments(c, args);
1822 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001824 }
1825
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001826 annotations = compiler_visit_annotations(c, args, returns);
1827 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001828 return 0;
1829 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001830 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001831 funcflags |= 0x04;
1832 }
1833
1834 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1835 return 0;
1836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837
INADA Naokicb41b272017-02-23 00:31:59 +09001838 /* if not -OO mode, add docstring */
1839 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1840 docstring = s->v.FunctionDef.docstring;
1841 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 compiler_exit_scope(c);
1843 return 0;
1844 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 c->u->u_argcount = asdl_seq_LEN(args->args);
1847 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001849 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001851 qualname = c->u->u_qualname;
1852 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001854 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001855 Py_XDECREF(qualname);
1856 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001860 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001861 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* decorators */
1865 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1866 ADDOP_I(c, CALL_FUNCTION, 1);
1867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868
Yury Selivanov75445082015-05-11 22:57:16 -04001869 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870}
1871
1872static int
1873compiler_class(struct compiler *c, stmt_ty s)
1874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 PyCodeObject *co;
1876 PyObject *str;
1877 int i;
1878 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (!compiler_decorators(c, decos))
1881 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* ultimately generate code for:
1884 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1885 where:
1886 <func> is a function/closure created from the class body;
1887 it has a single argument (__locals__) where the dict
1888 (or MutableSequence) representing the locals is passed
1889 <name> is the class name
1890 <bases> is the positional arguments and *varargs argument
1891 <keywords> is the keyword arguments and **kwds argument
1892 This borrows from compiler_call.
1893 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001896 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1897 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return 0;
1899 /* this block represents what we do in the new scope */
1900 {
1901 /* use the class name for name mangling */
1902 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001903 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* load (global) __name__ ... */
1905 str = PyUnicode_InternFromString("__name__");
1906 if (!str || !compiler_nameop(c, str, Load)) {
1907 Py_XDECREF(str);
1908 compiler_exit_scope(c);
1909 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 Py_DECREF(str);
1912 /* ... and store it as __module__ */
1913 str = PyUnicode_InternFromString("__module__");
1914 if (!str || !compiler_nameop(c, str, Store)) {
1915 Py_XDECREF(str);
1916 compiler_exit_scope(c);
1917 return 0;
1918 }
1919 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001920 assert(c->u->u_qualname);
1921 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001922 str = PyUnicode_InternFromString("__qualname__");
1923 if (!str || !compiler_nameop(c, str, Store)) {
1924 Py_XDECREF(str);
1925 compiler_exit_scope(c);
1926 return 0;
1927 }
1928 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001930 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 compiler_exit_scope(c);
1932 return 0;
1933 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001934 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001935 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001936 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001937 str = PyUnicode_InternFromString("__class__");
1938 if (str == NULL) {
1939 compiler_exit_scope(c);
1940 return 0;
1941 }
1942 i = compiler_lookup_arg(c->u->u_cellvars, str);
1943 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001944 if (i < 0) {
1945 compiler_exit_scope(c);
1946 return 0;
1947 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001948 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001951 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001952 str = PyUnicode_InternFromString("__classcell__");
1953 if (!str || !compiler_nameop(c, str, Store)) {
1954 Py_XDECREF(str);
1955 compiler_exit_scope(c);
1956 return 0;
1957 }
1958 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001960 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001961 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001962 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001963 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001964 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001965 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 /* create the code object */
1967 co = assemble(c, 1);
1968 }
1969 /* leave the new scope */
1970 compiler_exit_scope(c);
1971 if (co == NULL)
1972 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* 2. load the 'build_class' function */
1975 ADDOP(c, LOAD_BUILD_CLASS);
1976
1977 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001978 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 Py_DECREF(co);
1980
1981 /* 4. load class name */
1982 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1983
1984 /* 5. generate the rest of the code for the call */
1985 if (!compiler_call_helper(c, 2,
1986 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001987 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return 0;
1989
1990 /* 6. apply decorators */
1991 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1992 ADDOP_I(c, CALL_FUNCTION, 1);
1993 }
1994
1995 /* 7. store into <name> */
1996 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1997 return 0;
1998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999}
2000
2001static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002002cmpop(cmpop_ty op)
2003{
2004 switch (op) {
2005 case Eq:
2006 return PyCmp_EQ;
2007 case NotEq:
2008 return PyCmp_NE;
2009 case Lt:
2010 return PyCmp_LT;
2011 case LtE:
2012 return PyCmp_LE;
2013 case Gt:
2014 return PyCmp_GT;
2015 case GtE:
2016 return PyCmp_GE;
2017 case Is:
2018 return PyCmp_IS;
2019 case IsNot:
2020 return PyCmp_IS_NOT;
2021 case In:
2022 return PyCmp_IN;
2023 case NotIn:
2024 return PyCmp_NOT_IN;
2025 default:
2026 return PyCmp_BAD;
2027 }
2028}
2029
2030static int
2031compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2032{
2033 switch (e->kind) {
2034 case UnaryOp_kind:
2035 if (e->v.UnaryOp.op == Not)
2036 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2037 /* fallback to general implementation */
2038 break;
2039 case BoolOp_kind: {
2040 asdl_seq *s = e->v.BoolOp.values;
2041 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2042 assert(n >= 0);
2043 int cond2 = e->v.BoolOp.op == Or;
2044 basicblock *next2 = next;
2045 if (!cond2 != !cond) {
2046 next2 = compiler_new_block(c);
2047 if (next2 == NULL)
2048 return 0;
2049 }
2050 for (i = 0; i < n; ++i) {
2051 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2052 return 0;
2053 }
2054 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2055 return 0;
2056 if (next2 != next)
2057 compiler_use_next_block(c, next2);
2058 return 1;
2059 }
2060 case IfExp_kind: {
2061 basicblock *end, *next2;
2062 end = compiler_new_block(c);
2063 if (end == NULL)
2064 return 0;
2065 next2 = compiler_new_block(c);
2066 if (next2 == NULL)
2067 return 0;
2068 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2069 return 0;
2070 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2071 return 0;
2072 ADDOP_JREL(c, JUMP_FORWARD, end);
2073 compiler_use_next_block(c, next2);
2074 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2075 return 0;
2076 compiler_use_next_block(c, end);
2077 return 1;
2078 }
2079 case Compare_kind: {
2080 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2081 if (n > 0) {
2082 basicblock *cleanup = compiler_new_block(c);
2083 if (cleanup == NULL)
2084 return 0;
2085 VISIT(c, expr, e->v.Compare.left);
2086 for (i = 0; i < n; i++) {
2087 VISIT(c, expr,
2088 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2089 ADDOP(c, DUP_TOP);
2090 ADDOP(c, ROT_THREE);
2091 ADDOP_I(c, COMPARE_OP,
2092 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2093 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2094 NEXT_BLOCK(c);
2095 }
2096 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2097 ADDOP_I(c, COMPARE_OP,
2098 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2099 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2100 basicblock *end = compiler_new_block(c);
2101 if (end == NULL)
2102 return 0;
2103 ADDOP_JREL(c, JUMP_FORWARD, end);
2104 compiler_use_next_block(c, cleanup);
2105 ADDOP(c, POP_TOP);
2106 if (!cond) {
2107 ADDOP_JREL(c, JUMP_FORWARD, next);
2108 }
2109 compiler_use_next_block(c, end);
2110 return 1;
2111 }
2112 /* fallback to general implementation */
2113 break;
2114 }
2115 default:
2116 /* fallback to general implementation */
2117 break;
2118 }
2119
2120 /* general implementation */
2121 VISIT(c, expr, e);
2122 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2123 return 1;
2124}
2125
2126static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002127compiler_ifexp(struct compiler *c, expr_ty e)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 basicblock *end, *next;
2130
2131 assert(e->kind == IfExp_kind);
2132 end = compiler_new_block(c);
2133 if (end == NULL)
2134 return 0;
2135 next = compiler_new_block(c);
2136 if (next == NULL)
2137 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002138 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2139 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 VISIT(c, expr, e->v.IfExp.body);
2141 ADDOP_JREL(c, JUMP_FORWARD, end);
2142 compiler_use_next_block(c, next);
2143 VISIT(c, expr, e->v.IfExp.orelse);
2144 compiler_use_next_block(c, end);
2145 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002146}
2147
2148static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149compiler_lambda(struct compiler *c, expr_ty e)
2150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002152 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 arguments_ty args = e->v.Lambda.args;
2156 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (!name) {
2159 name = PyUnicode_InternFromString("<lambda>");
2160 if (!name)
2161 return 0;
2162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002164 funcflags = compiler_default_arguments(c, args);
2165 if (funcflags == -1) {
2166 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002168
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002169 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002170 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* Make None the first constant, so the lambda can't have a
2174 docstring. */
2175 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2176 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 c->u->u_argcount = asdl_seq_LEN(args->args);
2179 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2180 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2181 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002182 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
2184 else {
2185 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002186 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002188 qualname = c->u->u_qualname;
2189 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002191 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002194 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002195 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_DECREF(co);
2197
2198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199}
2200
2201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202compiler_if(struct compiler *c, stmt_ty s)
2203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 basicblock *end, *next;
2205 int constant;
2206 assert(s->kind == If_kind);
2207 end = compiler_new_block(c);
2208 if (end == NULL)
2209 return 0;
2210
Georg Brandl8334fd92010-12-04 10:26:46 +00002211 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* constant = 0: "if 0"
2213 * constant = 1: "if 1", "if 2", ...
2214 * constant = -1: rest */
2215 if (constant == 0) {
2216 if (s->v.If.orelse)
2217 VISIT_SEQ(c, stmt, s->v.If.orelse);
2218 } else if (constant == 1) {
2219 VISIT_SEQ(c, stmt, s->v.If.body);
2220 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002221 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 next = compiler_new_block(c);
2223 if (next == NULL)
2224 return 0;
2225 }
2226 else
2227 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002228 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2229 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002231 if (asdl_seq_LEN(s->v.If.orelse)) {
2232 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 compiler_use_next_block(c, next);
2234 VISIT_SEQ(c, stmt, s->v.If.orelse);
2235 }
2236 }
2237 compiler_use_next_block(c, end);
2238 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239}
2240
2241static int
2242compiler_for(struct compiler *c, stmt_ty s)
2243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 start = compiler_new_block(c);
2247 cleanup = compiler_new_block(c);
2248 end = compiler_new_block(c);
2249 if (start == NULL || end == NULL || cleanup == NULL)
2250 return 0;
2251 ADDOP_JREL(c, SETUP_LOOP, end);
2252 if (!compiler_push_fblock(c, LOOP, start))
2253 return 0;
2254 VISIT(c, expr, s->v.For.iter);
2255 ADDOP(c, GET_ITER);
2256 compiler_use_next_block(c, start);
2257 ADDOP_JREL(c, FOR_ITER, cleanup);
2258 VISIT(c, expr, s->v.For.target);
2259 VISIT_SEQ(c, stmt, s->v.For.body);
2260 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2261 compiler_use_next_block(c, cleanup);
2262 ADDOP(c, POP_BLOCK);
2263 compiler_pop_fblock(c, LOOP, start);
2264 VISIT_SEQ(c, stmt, s->v.For.orelse);
2265 compiler_use_next_block(c, end);
2266 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267}
2268
Yury Selivanov75445082015-05-11 22:57:16 -04002269
2270static int
2271compiler_async_for(struct compiler *c, stmt_ty s)
2272{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002273 _Py_IDENTIFIER(StopAsyncIteration);
2274
Yury Selivanov75445082015-05-11 22:57:16 -04002275 basicblock *try, *except, *end, *after_try, *try_cleanup,
2276 *after_loop, *after_loop_else;
2277
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002278 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2279 if (stop_aiter_error == NULL) {
2280 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002281 }
2282
2283 try = compiler_new_block(c);
2284 except = compiler_new_block(c);
2285 end = compiler_new_block(c);
2286 after_try = compiler_new_block(c);
2287 try_cleanup = compiler_new_block(c);
2288 after_loop = compiler_new_block(c);
2289 after_loop_else = compiler_new_block(c);
2290
2291 if (try == NULL || except == NULL || end == NULL
2292 || after_try == NULL || try_cleanup == NULL)
2293 return 0;
2294
2295 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2296 if (!compiler_push_fblock(c, LOOP, try))
2297 return 0;
2298
2299 VISIT(c, expr, s->v.AsyncFor.iter);
2300 ADDOP(c, GET_AITER);
2301 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2302 ADDOP(c, YIELD_FROM);
2303
2304 compiler_use_next_block(c, try);
2305
2306
2307 ADDOP_JREL(c, SETUP_EXCEPT, except);
2308 if (!compiler_push_fblock(c, EXCEPT, try))
2309 return 0;
2310
2311 ADDOP(c, GET_ANEXT);
2312 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2313 ADDOP(c, YIELD_FROM);
2314 VISIT(c, expr, s->v.AsyncFor.target);
2315 ADDOP(c, POP_BLOCK);
2316 compiler_pop_fblock(c, EXCEPT, try);
2317 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2318
2319
2320 compiler_use_next_block(c, except);
2321 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002322 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002323 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2324 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2325
2326 ADDOP(c, POP_TOP);
2327 ADDOP(c, POP_TOP);
2328 ADDOP(c, POP_TOP);
2329 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2330 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2331 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2332
2333
2334 compiler_use_next_block(c, try_cleanup);
2335 ADDOP(c, END_FINALLY);
2336
2337 compiler_use_next_block(c, after_try);
2338 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2339 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2340
2341 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2342 compiler_pop_fblock(c, LOOP, try);
2343
2344 compiler_use_next_block(c, after_loop);
2345 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2346
2347 compiler_use_next_block(c, after_loop_else);
2348 VISIT_SEQ(c, stmt, s->v.For.orelse);
2349
2350 compiler_use_next_block(c, end);
2351
2352 return 1;
2353}
2354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355static int
2356compiler_while(struct compiler *c, stmt_ty s)
2357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002359 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (constant == 0) {
2362 if (s->v.While.orelse)
2363 VISIT_SEQ(c, stmt, s->v.While.orelse);
2364 return 1;
2365 }
2366 loop = compiler_new_block(c);
2367 end = compiler_new_block(c);
2368 if (constant == -1) {
2369 anchor = compiler_new_block(c);
2370 if (anchor == NULL)
2371 return 0;
2372 }
2373 if (loop == NULL || end == NULL)
2374 return 0;
2375 if (s->v.While.orelse) {
2376 orelse = compiler_new_block(c);
2377 if (orelse == NULL)
2378 return 0;
2379 }
2380 else
2381 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 ADDOP_JREL(c, SETUP_LOOP, end);
2384 compiler_use_next_block(c, loop);
2385 if (!compiler_push_fblock(c, LOOP, loop))
2386 return 0;
2387 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002388 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2389 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 }
2391 VISIT_SEQ(c, stmt, s->v.While.body);
2392 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* XXX should the two POP instructions be in a separate block
2395 if there is no else clause ?
2396 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002398 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002400 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 compiler_pop_fblock(c, LOOP, loop);
2402 if (orelse != NULL) /* what if orelse is just pass? */
2403 VISIT_SEQ(c, stmt, s->v.While.orelse);
2404 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407}
2408
2409static int
2410compiler_continue(struct compiler *c)
2411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2413 static const char IN_FINALLY_ERROR_MSG[] =
2414 "'continue' not supported inside 'finally' clause";
2415 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (!c->u->u_nfblocks)
2418 return compiler_error(c, LOOP_ERROR_MSG);
2419 i = c->u->u_nfblocks - 1;
2420 switch (c->u->u_fblock[i].fb_type) {
2421 case LOOP:
2422 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2423 break;
2424 case EXCEPT:
2425 case FINALLY_TRY:
2426 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2427 /* Prevent continue anywhere under a finally
2428 even if hidden in a sub-try or except. */
2429 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2430 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2431 }
2432 if (i == -1)
2433 return compiler_error(c, LOOP_ERROR_MSG);
2434 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2435 break;
2436 case FINALLY_END:
2437 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2438 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441}
2442
2443/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444
2445 SETUP_FINALLY L
2446 <code for body>
2447 POP_BLOCK
2448 LOAD_CONST <None>
2449 L: <code for finalbody>
2450 END_FINALLY
2451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452 The special instructions use the block stack. Each block
2453 stack entry contains the instruction that created it (here
2454 SETUP_FINALLY), the level of the value stack at the time the
2455 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Pushes the current value stack level and the label
2459 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 Pops en entry from the block stack, and pops the value
2462 stack until its level is the same as indicated on the
2463 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 Pops a variable number of entries from the *value* stack
2466 and re-raises the exception they specify. The number of
2467 entries popped depends on the (pseudo) exception type.
2468
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 The block stack is unwound when an exception is raised:
2470 when a SETUP_FINALLY entry is found, the exception is pushed
2471 onto the value stack (and the exception condition is cleared),
2472 and the interpreter jumps to the label gotten from the block
2473 stack.
2474*/
2475
2476static int
2477compiler_try_finally(struct compiler *c, stmt_ty s)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 basicblock *body, *end;
2480 body = compiler_new_block(c);
2481 end = compiler_new_block(c);
2482 if (body == NULL || end == NULL)
2483 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 ADDOP_JREL(c, SETUP_FINALLY, end);
2486 compiler_use_next_block(c, body);
2487 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2488 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002489 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2490 if (!compiler_try_except(c, s))
2491 return 0;
2492 }
2493 else {
2494 VISIT_SEQ(c, stmt, s->v.Try.body);
2495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 ADDOP(c, POP_BLOCK);
2497 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2500 compiler_use_next_block(c, end);
2501 if (!compiler_push_fblock(c, FINALLY_END, end))
2502 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002503 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 ADDOP(c, END_FINALLY);
2505 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508}
2509
2510/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002511 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 (The contents of the value stack is shown in [], with the top
2513 at the right; 'tb' is trace-back info, 'val' the exception's
2514 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515
2516 Value stack Label Instruction Argument
2517 [] SETUP_EXCEPT L1
2518 [] <code for S>
2519 [] POP_BLOCK
2520 [] JUMP_FORWARD L0
2521
2522 [tb, val, exc] L1: DUP )
2523 [tb, val, exc, exc] <evaluate E1> )
2524 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2525 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2526 [tb, val, exc] POP
2527 [tb, val] <assign to V1> (or POP if no V1)
2528 [tb] POP
2529 [] <code for S1>
2530 JUMP_FORWARD L0
2531
2532 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 .............................etc.......................
2534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2536
2537 [] L0: <next statement>
2538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 Of course, parts are not generated if Vi or Ei is not present.
2540*/
2541static int
2542compiler_try_except(struct compiler *c, stmt_ty s)
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002545 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 body = compiler_new_block(c);
2548 except = compiler_new_block(c);
2549 orelse = compiler_new_block(c);
2550 end = compiler_new_block(c);
2551 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2552 return 0;
2553 ADDOP_JREL(c, SETUP_EXCEPT, except);
2554 compiler_use_next_block(c, body);
2555 if (!compiler_push_fblock(c, EXCEPT, body))
2556 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002557 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 ADDOP(c, POP_BLOCK);
2559 compiler_pop_fblock(c, EXCEPT, body);
2560 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002561 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 compiler_use_next_block(c, except);
2563 for (i = 0; i < n; i++) {
2564 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002565 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (!handler->v.ExceptHandler.type && i < n-1)
2567 return compiler_error(c, "default 'except:' must be last");
2568 c->u->u_lineno_set = 0;
2569 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002570 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 except = compiler_new_block(c);
2572 if (except == NULL)
2573 return 0;
2574 if (handler->v.ExceptHandler.type) {
2575 ADDOP(c, DUP_TOP);
2576 VISIT(c, expr, handler->v.ExceptHandler.type);
2577 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2578 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2579 }
2580 ADDOP(c, POP_TOP);
2581 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002582 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002583
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002584 cleanup_end = compiler_new_block(c);
2585 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002586 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002587 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002588
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002589 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2590 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002592 /*
2593 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002594 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002595 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002596 try:
2597 # body
2598 finally:
2599 name = None
2600 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002601 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002603 /* second try: */
2604 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2605 compiler_use_next_block(c, cleanup_body);
2606 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2607 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002609 /* second # body */
2610 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2611 ADDOP(c, POP_BLOCK);
2612 ADDOP(c, POP_EXCEPT);
2613 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002615 /* finally: */
2616 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2617 compiler_use_next_block(c, cleanup_end);
2618 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2619 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002621 /* name = None */
2622 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2623 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002625 /* del name */
2626 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002628 ADDOP(c, END_FINALLY);
2629 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 }
2631 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002632 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002634 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002635 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002636 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637
Guido van Rossumb940e112007-01-10 16:19:56 +00002638 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002639 ADDOP(c, POP_TOP);
2640 compiler_use_next_block(c, cleanup_body);
2641 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2642 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002644 ADDOP(c, POP_EXCEPT);
2645 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
2647 ADDOP_JREL(c, JUMP_FORWARD, end);
2648 compiler_use_next_block(c, except);
2649 }
2650 ADDOP(c, END_FINALLY);
2651 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002652 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 compiler_use_next_block(c, end);
2654 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655}
2656
2657static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002658compiler_try(struct compiler *c, stmt_ty s) {
2659 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2660 return compiler_try_finally(c, s);
2661 else
2662 return compiler_try_except(c, s);
2663}
2664
2665
2666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667compiler_import_as(struct compiler *c, identifier name, identifier asname)
2668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 /* The IMPORT_NAME opcode was already generated. This function
2670 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002673 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002675 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2676 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002678 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002679 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002681 while (1) {
2682 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002684 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002685 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002686 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002687 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002689 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002690 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002692 if (dot == -1) {
2693 break;
2694 }
2695 ADDOP(c, ROT_TWO);
2696 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002698 if (!compiler_nameop(c, asname, Store)) {
2699 return 0;
2700 }
2701 ADDOP(c, POP_TOP);
2702 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 }
2704 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705}
2706
2707static int
2708compiler_import(struct compiler *c, stmt_ty s)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 /* The Import node stores a module name like a.b.c as a single
2711 string. This is convenient for all cases except
2712 import a.b.c as d
2713 where we need to parse that string to extract the individual
2714 module names.
2715 XXX Perhaps change the representation to make this case simpler?
2716 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002717 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 for (i = 0; i < n; i++) {
2720 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2721 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002723 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2725 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (alias->asname) {
2728 r = compiler_import_as(c, alias->name, alias->asname);
2729 if (!r)
2730 return r;
2731 }
2732 else {
2733 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 Py_ssize_t dot = PyUnicode_FindChar(
2735 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002736 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002738 if (tmp == NULL)
2739 return 0;
2740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 Py_DECREF(tmp);
2744 }
2745 if (!r)
2746 return r;
2747 }
2748 }
2749 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750}
2751
2752static int
2753compiler_from_import(struct compiler *c, stmt_ty s)
2754{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002755 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 PyObject *names = PyTuple_New(n);
2758 PyObject *level;
2759 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 if (!empty_string) {
2762 empty_string = PyUnicode_FromString("");
2763 if (!empty_string)
2764 return 0;
2765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 if (!names)
2768 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 level = PyLong_FromLong(s->v.ImportFrom.level);
2771 if (!level) {
2772 Py_DECREF(names);
2773 return 0;
2774 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 /* build up the names */
2777 for (i = 0; i < n; i++) {
2778 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2779 Py_INCREF(alias->name);
2780 PyTuple_SET_ITEM(names, i, alias->name);
2781 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002784 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 Py_DECREF(level);
2786 Py_DECREF(names);
2787 return compiler_error(c, "from __future__ imports must occur "
2788 "at the beginning of the file");
2789 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 ADDOP_O(c, LOAD_CONST, level, consts);
2792 Py_DECREF(level);
2793 ADDOP_O(c, LOAD_CONST, names, consts);
2794 Py_DECREF(names);
2795 if (s->v.ImportFrom.module) {
2796 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2797 }
2798 else {
2799 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2800 }
2801 for (i = 0; i < n; i++) {
2802 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2803 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 assert(n == 1);
2807 ADDOP(c, IMPORT_STAR);
2808 return 1;
2809 }
2810
2811 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2812 store_name = alias->name;
2813 if (alias->asname)
2814 store_name = alias->asname;
2815
2816 if (!compiler_nameop(c, store_name, Store)) {
2817 Py_DECREF(names);
2818 return 0;
2819 }
2820 }
2821 /* remove imported module */
2822 ADDOP(c, POP_TOP);
2823 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824}
2825
2826static int
2827compiler_assert(struct compiler *c, stmt_ty s)
2828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 static PyObject *assertion_error = NULL;
2830 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002831 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Georg Brandl8334fd92010-12-04 10:26:46 +00002833 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 return 1;
2835 if (assertion_error == NULL) {
2836 assertion_error = PyUnicode_InternFromString("AssertionError");
2837 if (assertion_error == NULL)
2838 return 0;
2839 }
2840 if (s->v.Assert.test->kind == Tuple_kind &&
2841 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002842 msg = PyUnicode_FromString("assertion is always true, "
2843 "perhaps remove parentheses?");
2844 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002846 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2847 c->c_filename, c->u->u_lineno,
2848 NULL, NULL) == -1) {
2849 Py_DECREF(msg);
2850 return 0;
2851 }
2852 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 end = compiler_new_block(c);
2855 if (end == NULL)
2856 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002857 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2858 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2860 if (s->v.Assert.msg) {
2861 VISIT(c, expr, s->v.Assert.msg);
2862 ADDOP_I(c, CALL_FUNCTION, 1);
2863 }
2864 ADDOP_I(c, RAISE_VARARGS, 1);
2865 compiler_use_next_block(c, end);
2866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867}
2868
2869static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002870compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2871{
2872 if (c->c_interactive && c->c_nestlevel <= 1) {
2873 VISIT(c, expr, value);
2874 ADDOP(c, PRINT_EXPR);
2875 return 1;
2876 }
2877
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002878 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002879 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002880 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002881 }
2882
2883 VISIT(c, expr, value);
2884 ADDOP(c, POP_TOP);
2885 return 1;
2886}
2887
2888static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889compiler_visit_stmt(struct compiler *c, stmt_ty s)
2890{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002891 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 /* Always assign a lineno to the next instruction for a stmt. */
2894 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002895 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 switch (s->kind) {
2899 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002900 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 case ClassDef_kind:
2902 return compiler_class(c, s);
2903 case Return_kind:
2904 if (c->u->u_ste->ste_type != FunctionBlock)
2905 return compiler_error(c, "'return' outside function");
2906 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002907 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2908 return compiler_error(
2909 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 VISIT(c, expr, s->v.Return.value);
2911 }
2912 else
2913 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2914 ADDOP(c, RETURN_VALUE);
2915 break;
2916 case Delete_kind:
2917 VISIT_SEQ(c, expr, s->v.Delete.targets)
2918 break;
2919 case Assign_kind:
2920 n = asdl_seq_LEN(s->v.Assign.targets);
2921 VISIT(c, expr, s->v.Assign.value);
2922 for (i = 0; i < n; i++) {
2923 if (i < n - 1)
2924 ADDOP(c, DUP_TOP);
2925 VISIT(c, expr,
2926 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2927 }
2928 break;
2929 case AugAssign_kind:
2930 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002931 case AnnAssign_kind:
2932 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 case For_kind:
2934 return compiler_for(c, s);
2935 case While_kind:
2936 return compiler_while(c, s);
2937 case If_kind:
2938 return compiler_if(c, s);
2939 case Raise_kind:
2940 n = 0;
2941 if (s->v.Raise.exc) {
2942 VISIT(c, expr, s->v.Raise.exc);
2943 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002944 if (s->v.Raise.cause) {
2945 VISIT(c, expr, s->v.Raise.cause);
2946 n++;
2947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002949 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002951 case Try_kind:
2952 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 case Assert_kind:
2954 return compiler_assert(c, s);
2955 case Import_kind:
2956 return compiler_import(c, s);
2957 case ImportFrom_kind:
2958 return compiler_from_import(c, s);
2959 case Global_kind:
2960 case Nonlocal_kind:
2961 break;
2962 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002963 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 case Pass_kind:
2965 break;
2966 case Break_kind:
2967 if (!compiler_in_loop(c))
2968 return compiler_error(c, "'break' outside loop");
2969 ADDOP(c, BREAK_LOOP);
2970 break;
2971 case Continue_kind:
2972 return compiler_continue(c);
2973 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002974 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002975 case AsyncFunctionDef_kind:
2976 return compiler_function(c, s, 1);
2977 case AsyncWith_kind:
2978 return compiler_async_with(c, s, 0);
2979 case AsyncFor_kind:
2980 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 }
Yury Selivanov75445082015-05-11 22:57:16 -04002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984}
2985
2986static int
2987unaryop(unaryop_ty op)
2988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 switch (op) {
2990 case Invert:
2991 return UNARY_INVERT;
2992 case Not:
2993 return UNARY_NOT;
2994 case UAdd:
2995 return UNARY_POSITIVE;
2996 case USub:
2997 return UNARY_NEGATIVE;
2998 default:
2999 PyErr_Format(PyExc_SystemError,
3000 "unary op %d should not be possible", op);
3001 return 0;
3002 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003}
3004
3005static int
3006binop(struct compiler *c, operator_ty op)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 switch (op) {
3009 case Add:
3010 return BINARY_ADD;
3011 case Sub:
3012 return BINARY_SUBTRACT;
3013 case Mult:
3014 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003015 case MatMult:
3016 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 case Div:
3018 return BINARY_TRUE_DIVIDE;
3019 case Mod:
3020 return BINARY_MODULO;
3021 case Pow:
3022 return BINARY_POWER;
3023 case LShift:
3024 return BINARY_LSHIFT;
3025 case RShift:
3026 return BINARY_RSHIFT;
3027 case BitOr:
3028 return BINARY_OR;
3029 case BitXor:
3030 return BINARY_XOR;
3031 case BitAnd:
3032 return BINARY_AND;
3033 case FloorDiv:
3034 return BINARY_FLOOR_DIVIDE;
3035 default:
3036 PyErr_Format(PyExc_SystemError,
3037 "binary op %d should not be possible", op);
3038 return 0;
3039 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040}
3041
3042static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043inplace_binop(struct compiler *c, operator_ty op)
3044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 switch (op) {
3046 case Add:
3047 return INPLACE_ADD;
3048 case Sub:
3049 return INPLACE_SUBTRACT;
3050 case Mult:
3051 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003052 case MatMult:
3053 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 case Div:
3055 return INPLACE_TRUE_DIVIDE;
3056 case Mod:
3057 return INPLACE_MODULO;
3058 case Pow:
3059 return INPLACE_POWER;
3060 case LShift:
3061 return INPLACE_LSHIFT;
3062 case RShift:
3063 return INPLACE_RSHIFT;
3064 case BitOr:
3065 return INPLACE_OR;
3066 case BitXor:
3067 return INPLACE_XOR;
3068 case BitAnd:
3069 return INPLACE_AND;
3070 case FloorDiv:
3071 return INPLACE_FLOOR_DIVIDE;
3072 default:
3073 PyErr_Format(PyExc_SystemError,
3074 "inplace binary op %d should not be possible", op);
3075 return 0;
3076 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077}
3078
3079static int
3080compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3081{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003082 int op, scope;
3083 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 PyObject *dict = c->u->u_names;
3087 PyObject *mangled;
3088 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 mangled = _Py_Mangle(c->u->u_private, name);
3091 if (!mangled)
3092 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003093
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003094 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3095 !_PyUnicode_EqualToASCIIString(name, "True") &&
3096 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 op = 0;
3099 optype = OP_NAME;
3100 scope = PyST_GetScope(c->u->u_ste, mangled);
3101 switch (scope) {
3102 case FREE:
3103 dict = c->u->u_freevars;
3104 optype = OP_DEREF;
3105 break;
3106 case CELL:
3107 dict = c->u->u_cellvars;
3108 optype = OP_DEREF;
3109 break;
3110 case LOCAL:
3111 if (c->u->u_ste->ste_type == FunctionBlock)
3112 optype = OP_FAST;
3113 break;
3114 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003115 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 optype = OP_GLOBAL;
3117 break;
3118 case GLOBAL_EXPLICIT:
3119 optype = OP_GLOBAL;
3120 break;
3121 default:
3122 /* scope can be 0 */
3123 break;
3124 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003127 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 switch (optype) {
3130 case OP_DEREF:
3131 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003132 case Load:
3133 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3134 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 case Store: op = STORE_DEREF; break;
3136 case AugLoad:
3137 case AugStore:
3138 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003139 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 case Param:
3141 default:
3142 PyErr_SetString(PyExc_SystemError,
3143 "param invalid for deref variable");
3144 return 0;
3145 }
3146 break;
3147 case OP_FAST:
3148 switch (ctx) {
3149 case Load: op = LOAD_FAST; break;
3150 case Store: op = STORE_FAST; break;
3151 case Del: op = DELETE_FAST; break;
3152 case AugLoad:
3153 case AugStore:
3154 break;
3155 case Param:
3156 default:
3157 PyErr_SetString(PyExc_SystemError,
3158 "param invalid for local variable");
3159 return 0;
3160 }
3161 ADDOP_O(c, op, mangled, varnames);
3162 Py_DECREF(mangled);
3163 return 1;
3164 case OP_GLOBAL:
3165 switch (ctx) {
3166 case Load: op = LOAD_GLOBAL; break;
3167 case Store: op = STORE_GLOBAL; break;
3168 case Del: op = DELETE_GLOBAL; break;
3169 case AugLoad:
3170 case AugStore:
3171 break;
3172 case Param:
3173 default:
3174 PyErr_SetString(PyExc_SystemError,
3175 "param invalid for global variable");
3176 return 0;
3177 }
3178 break;
3179 case OP_NAME:
3180 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003181 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 case Store: op = STORE_NAME; break;
3183 case Del: op = DELETE_NAME; break;
3184 case AugLoad:
3185 case AugStore:
3186 break;
3187 case Param:
3188 default:
3189 PyErr_SetString(PyExc_SystemError,
3190 "param invalid for name variable");
3191 return 0;
3192 }
3193 break;
3194 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 assert(op);
3197 arg = compiler_add_o(c, dict, mangled);
3198 Py_DECREF(mangled);
3199 if (arg < 0)
3200 return 0;
3201 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202}
3203
3204static int
3205compiler_boolop(struct compiler *c, expr_ty e)
3206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003208 int jumpi;
3209 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 assert(e->kind == BoolOp_kind);
3213 if (e->v.BoolOp.op == And)
3214 jumpi = JUMP_IF_FALSE_OR_POP;
3215 else
3216 jumpi = JUMP_IF_TRUE_OR_POP;
3217 end = compiler_new_block(c);
3218 if (end == NULL)
3219 return 0;
3220 s = e->v.BoolOp.values;
3221 n = asdl_seq_LEN(s) - 1;
3222 assert(n >= 0);
3223 for (i = 0; i < n; ++i) {
3224 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3225 ADDOP_JABS(c, jumpi, end);
3226 }
3227 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3228 compiler_use_next_block(c, end);
3229 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230}
3231
3232static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003233starunpack_helper(struct compiler *c, asdl_seq *elts,
3234 int single_op, int inner_op, int outer_op)
3235{
3236 Py_ssize_t n = asdl_seq_LEN(elts);
3237 Py_ssize_t i, nsubitems = 0, nseen = 0;
3238 for (i = 0; i < n; i++) {
3239 expr_ty elt = asdl_seq_GET(elts, i);
3240 if (elt->kind == Starred_kind) {
3241 if (nseen) {
3242 ADDOP_I(c, inner_op, nseen);
3243 nseen = 0;
3244 nsubitems++;
3245 }
3246 VISIT(c, expr, elt->v.Starred.value);
3247 nsubitems++;
3248 }
3249 else {
3250 VISIT(c, expr, elt);
3251 nseen++;
3252 }
3253 }
3254 if (nsubitems) {
3255 if (nseen) {
3256 ADDOP_I(c, inner_op, nseen);
3257 nsubitems++;
3258 }
3259 ADDOP_I(c, outer_op, nsubitems);
3260 }
3261 else
3262 ADDOP_I(c, single_op, nseen);
3263 return 1;
3264}
3265
3266static int
3267assignment_helper(struct compiler *c, asdl_seq *elts)
3268{
3269 Py_ssize_t n = asdl_seq_LEN(elts);
3270 Py_ssize_t i;
3271 int seen_star = 0;
3272 for (i = 0; i < n; i++) {
3273 expr_ty elt = asdl_seq_GET(elts, i);
3274 if (elt->kind == Starred_kind && !seen_star) {
3275 if ((i >= (1 << 8)) ||
3276 (n-i-1 >= (INT_MAX >> 8)))
3277 return compiler_error(c,
3278 "too many expressions in "
3279 "star-unpacking assignment");
3280 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3281 seen_star = 1;
3282 asdl_seq_SET(elts, i, elt->v.Starred.value);
3283 }
3284 else if (elt->kind == Starred_kind) {
3285 return compiler_error(c,
3286 "two starred expressions in assignment");
3287 }
3288 }
3289 if (!seen_star) {
3290 ADDOP_I(c, UNPACK_SEQUENCE, n);
3291 }
3292 VISIT_SEQ(c, expr, elts);
3293 return 1;
3294}
3295
3296static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297compiler_list(struct compiler *c, expr_ty e)
3298{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003299 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003301 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003303 else if (e->v.List.ctx == Load) {
3304 return starunpack_helper(c, elts,
3305 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003307 else
3308 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310}
3311
3312static int
3313compiler_tuple(struct compiler *c, expr_ty e)
3314{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003315 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003317 return assignment_helper(c, elts);
3318 }
3319 else if (e->v.Tuple.ctx == Load) {
3320 return starunpack_helper(c, elts,
3321 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3322 }
3323 else
3324 VISIT_SEQ(c, expr, elts);
3325 return 1;
3326}
3327
3328static int
3329compiler_set(struct compiler *c, expr_ty e)
3330{
3331 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3332 BUILD_SET, BUILD_SET_UNPACK);
3333}
3334
3335static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003336are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3337{
3338 Py_ssize_t i;
3339 for (i = begin; i < end; i++) {
3340 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3341 if (key == NULL || !is_const(key))
3342 return 0;
3343 }
3344 return 1;
3345}
3346
3347static int
3348compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3349{
3350 Py_ssize_t i, n = end - begin;
3351 PyObject *keys, *key;
3352 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3353 for (i = begin; i < end; i++) {
3354 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3355 }
3356 keys = PyTuple_New(n);
3357 if (keys == NULL) {
3358 return 0;
3359 }
3360 for (i = begin; i < end; i++) {
3361 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3362 Py_INCREF(key);
3363 PyTuple_SET_ITEM(keys, i - begin, key);
3364 }
3365 ADDOP_N(c, LOAD_CONST, keys, consts);
3366 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3367 }
3368 else {
3369 for (i = begin; i < end; i++) {
3370 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3371 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3372 }
3373 ADDOP_I(c, BUILD_MAP, n);
3374 }
3375 return 1;
3376}
3377
3378static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003379compiler_dict(struct compiler *c, expr_ty e)
3380{
Victor Stinner976bb402016-03-23 11:36:19 +01003381 Py_ssize_t i, n, elements;
3382 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003383 int is_unpacking = 0;
3384 n = asdl_seq_LEN(e->v.Dict.values);
3385 containers = 0;
3386 elements = 0;
3387 for (i = 0; i < n; i++) {
3388 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3389 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003390 if (!compiler_subdict(c, e, i - elements, i))
3391 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003392 containers++;
3393 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003395 if (is_unpacking) {
3396 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3397 containers++;
3398 }
3399 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003400 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 }
3402 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003403 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003404 if (!compiler_subdict(c, e, n - elements, n))
3405 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003406 containers++;
3407 }
3408 /* If there is more than one dict, they need to be merged into a new
3409 * dict. If there is one dict and it's an unpacking, then it needs
3410 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003411 if (containers > 1 || is_unpacking) {
3412 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 }
3414 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003415}
3416
3417static int
3418compiler_compare(struct compiler *c, expr_ty e)
3419{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003420 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3424 VISIT(c, expr, e->v.Compare.left);
3425 n = asdl_seq_LEN(e->v.Compare.ops);
3426 assert(n > 0);
3427 if (n > 1) {
3428 cleanup = compiler_new_block(c);
3429 if (cleanup == NULL)
3430 return 0;
3431 VISIT(c, expr,
3432 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3433 }
3434 for (i = 1; i < n; i++) {
3435 ADDOP(c, DUP_TOP);
3436 ADDOP(c, ROT_THREE);
3437 ADDOP_I(c, COMPARE_OP,
3438 cmpop((cmpop_ty)(asdl_seq_GET(
3439 e->v.Compare.ops, i - 1))));
3440 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3441 NEXT_BLOCK(c);
3442 if (i < (n - 1))
3443 VISIT(c, expr,
3444 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3445 }
3446 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3447 ADDOP_I(c, COMPARE_OP,
3448 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3449 if (n > 1) {
3450 basicblock *end = compiler_new_block(c);
3451 if (end == NULL)
3452 return 0;
3453 ADDOP_JREL(c, JUMP_FORWARD, end);
3454 compiler_use_next_block(c, cleanup);
3455 ADDOP(c, ROT_TWO);
3456 ADDOP(c, POP_TOP);
3457 compiler_use_next_block(c, end);
3458 }
3459 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460}
3461
3462static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003463maybe_optimize_method_call(struct compiler *c, expr_ty e)
3464{
3465 Py_ssize_t argsl, i;
3466 expr_ty meth = e->v.Call.func;
3467 asdl_seq *args = e->v.Call.args;
3468
3469 /* Check that the call node is an attribute access, and that
3470 the call doesn't have keyword parameters. */
3471 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3472 asdl_seq_LEN(e->v.Call.keywords))
3473 return -1;
3474
3475 /* Check that there are no *varargs types of arguments. */
3476 argsl = asdl_seq_LEN(args);
3477 for (i = 0; i < argsl; i++) {
3478 expr_ty elt = asdl_seq_GET(args, i);
3479 if (elt->kind == Starred_kind) {
3480 return -1;
3481 }
3482 }
3483
3484 /* Alright, we can optimize the code. */
3485 VISIT(c, expr, meth->v.Attribute.value);
3486 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3487 VISIT_SEQ(c, expr, e->v.Call.args);
3488 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3489 return 1;
3490}
3491
3492static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493compiler_call(struct compiler *c, expr_ty e)
3494{
Yury Selivanovf2392132016-12-13 19:03:51 -05003495 if (maybe_optimize_method_call(c, e) > 0)
3496 return 1;
3497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 VISIT(c, expr, e->v.Call.func);
3499 return compiler_call_helper(c, 0,
3500 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003501 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003502}
3503
Eric V. Smith235a6f02015-09-19 14:51:32 -04003504static int
3505compiler_joined_str(struct compiler *c, expr_ty e)
3506{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003507 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003508 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3509 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003510 return 1;
3511}
3512
Eric V. Smitha78c7952015-11-03 12:45:05 -05003513/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003514static int
3515compiler_formatted_value(struct compiler *c, expr_ty e)
3516{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003517 /* Our oparg encodes 2 pieces of information: the conversion
3518 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003519
Eric V. Smitha78c7952015-11-03 12:45:05 -05003520 Convert the conversion char to 2 bits:
3521 None: 000 0x0 FVC_NONE
3522 !s : 001 0x1 FVC_STR
3523 !r : 010 0x2 FVC_REPR
3524 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003525
Eric V. Smitha78c7952015-11-03 12:45:05 -05003526 next bit is whether or not we have a format spec:
3527 yes : 100 0x4
3528 no : 000 0x0
3529 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003530
Eric V. Smitha78c7952015-11-03 12:45:05 -05003531 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003532
Eric V. Smitha78c7952015-11-03 12:45:05 -05003533 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003534 VISIT(c, expr, e->v.FormattedValue.value);
3535
Eric V. Smitha78c7952015-11-03 12:45:05 -05003536 switch (e->v.FormattedValue.conversion) {
3537 case 's': oparg = FVC_STR; break;
3538 case 'r': oparg = FVC_REPR; break;
3539 case 'a': oparg = FVC_ASCII; break;
3540 case -1: oparg = FVC_NONE; break;
3541 default:
3542 PyErr_SetString(PyExc_SystemError,
3543 "Unrecognized conversion character");
3544 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003545 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003546 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003547 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003548 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003549 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003550 }
3551
Eric V. Smitha78c7952015-11-03 12:45:05 -05003552 /* And push our opcode and oparg */
3553 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003554 return 1;
3555}
3556
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003557static int
3558compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3559{
3560 Py_ssize_t i, n = end - begin;
3561 keyword_ty kw;
3562 PyObject *keys, *key;
3563 assert(n > 0);
3564 if (n > 1) {
3565 for (i = begin; i < end; i++) {
3566 kw = asdl_seq_GET(keywords, i);
3567 VISIT(c, expr, kw->value);
3568 }
3569 keys = PyTuple_New(n);
3570 if (keys == NULL) {
3571 return 0;
3572 }
3573 for (i = begin; i < end; i++) {
3574 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3575 Py_INCREF(key);
3576 PyTuple_SET_ITEM(keys, i - begin, key);
3577 }
3578 ADDOP_N(c, LOAD_CONST, keys, consts);
3579 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3580 }
3581 else {
3582 /* a for loop only executes once */
3583 for (i = begin; i < end; i++) {
3584 kw = asdl_seq_GET(keywords, i);
3585 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3586 VISIT(c, expr, kw->value);
3587 }
3588 ADDOP_I(c, BUILD_MAP, n);
3589 }
3590 return 1;
3591}
3592
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003593/* shared code between compiler_call and compiler_class */
3594static int
3595compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003596 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003597 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003598 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003599{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003600 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003601 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003602
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003603 /* the number of tuples and dictionaries on the stack */
3604 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3605
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003606 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003607 nkwelts = asdl_seq_LEN(keywords);
3608
3609 for (i = 0; i < nkwelts; i++) {
3610 keyword_ty kw = asdl_seq_GET(keywords, i);
3611 if (kw->arg == NULL) {
3612 mustdictunpack = 1;
3613 break;
3614 }
3615 }
3616
3617 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003618 for (i = 0; i < nelts; i++) {
3619 expr_ty elt = asdl_seq_GET(args, i);
3620 if (elt->kind == Starred_kind) {
3621 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003622 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003623 if (nseen) {
3624 ADDOP_I(c, BUILD_TUPLE, nseen);
3625 nseen = 0;
3626 nsubargs++;
3627 }
3628 VISIT(c, expr, elt->v.Starred.value);
3629 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003630 }
3631 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003632 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003633 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003636
3637 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003638 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003639 if (nseen) {
3640 /* Pack up any trailing positional arguments. */
3641 ADDOP_I(c, BUILD_TUPLE, nseen);
3642 nsubargs++;
3643 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003644 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003645 /* If we ended up with more than one stararg, we need
3646 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003647 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003648 }
3649 else if (nsubargs == 0) {
3650 ADDOP_I(c, BUILD_TUPLE, 0);
3651 }
3652 nseen = 0; /* the number of keyword arguments on the stack following */
3653 for (i = 0; i < nkwelts; i++) {
3654 keyword_ty kw = asdl_seq_GET(keywords, i);
3655 if (kw->arg == NULL) {
3656 /* A keyword argument unpacking. */
3657 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003658 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3659 return 0;
3660 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003661 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003662 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003663 VISIT(c, expr, kw->value);
3664 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003665 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003666 else {
3667 nseen++;
3668 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003669 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003670 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003671 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003672 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003673 return 0;
3674 nsubkwargs++;
3675 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003676 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003677 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003678 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003679 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003680 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3681 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003683 else if (nkwelts) {
3684 PyObject *names;
3685 VISIT_SEQ(c, keyword, keywords);
3686 names = PyTuple_New(nkwelts);
3687 if (names == NULL) {
3688 return 0;
3689 }
3690 for (i = 0; i < nkwelts; i++) {
3691 keyword_ty kw = asdl_seq_GET(keywords, i);
3692 Py_INCREF(kw->arg);
3693 PyTuple_SET_ITEM(names, i, kw->arg);
3694 }
3695 ADDOP_N(c, LOAD_CONST, names, consts);
3696 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3697 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003699 else {
3700 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3701 return 1;
3702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703}
3704
Nick Coghlan650f0d02007-04-15 12:05:43 +00003705
3706/* List and set comprehensions and generator expressions work by creating a
3707 nested function to perform the actual iteration. This means that the
3708 iteration variables don't leak into the current scope.
3709 The defined function is called immediately following its definition, with the
3710 result of that call being the result of the expression.
3711 The LC/SC version returns the populated container, while the GE version is
3712 flagged in symtable.c as a generator, so it returns the generator object
3713 when the function is called.
3714 This code *knows* that the loop cannot contain break, continue, or return,
3715 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3716
3717 Possible cleanups:
3718 - iterate over the generator sequence instead of using recursion
3719*/
3720
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003721
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723compiler_comprehension_generator(struct compiler *c,
3724 asdl_seq *generators, int gen_index,
3725 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003727 comprehension_ty gen;
3728 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3729 if (gen->is_async) {
3730 return compiler_async_comprehension_generator(
3731 c, generators, gen_index, elt, val, type);
3732 } else {
3733 return compiler_sync_comprehension_generator(
3734 c, generators, gen_index, elt, val, type);
3735 }
3736}
3737
3738static int
3739compiler_sync_comprehension_generator(struct compiler *c,
3740 asdl_seq *generators, int gen_index,
3741 expr_ty elt, expr_ty val, int type)
3742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 /* generate code for the iterator, then each of the ifs,
3744 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 comprehension_ty gen;
3747 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003748 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 start = compiler_new_block(c);
3751 skip = compiler_new_block(c);
3752 if_cleanup = compiler_new_block(c);
3753 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3756 anchor == NULL)
3757 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (gen_index == 0) {
3762 /* Receive outermost iter as an implicit argument */
3763 c->u->u_argcount = 1;
3764 ADDOP_I(c, LOAD_FAST, 0);
3765 }
3766 else {
3767 /* Sub-iter - calculate on the fly */
3768 VISIT(c, expr, gen->iter);
3769 ADDOP(c, GET_ITER);
3770 }
3771 compiler_use_next_block(c, start);
3772 ADDOP_JREL(c, FOR_ITER, anchor);
3773 NEXT_BLOCK(c);
3774 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 /* XXX this needs to be cleaned up...a lot! */
3777 n = asdl_seq_LEN(gen->ifs);
3778 for (i = 0; i < n; i++) {
3779 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003780 if (!compiler_jump_if(c, e, if_cleanup, 0))
3781 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 NEXT_BLOCK(c);
3783 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 if (++gen_index < asdl_seq_LEN(generators))
3786 if (!compiler_comprehension_generator(c,
3787 generators, gen_index,
3788 elt, val, type))
3789 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 /* only append after the last for generator */
3792 if (gen_index >= asdl_seq_LEN(generators)) {
3793 /* comprehension specific code */
3794 switch (type) {
3795 case COMP_GENEXP:
3796 VISIT(c, expr, elt);
3797 ADDOP(c, YIELD_VALUE);
3798 ADDOP(c, POP_TOP);
3799 break;
3800 case COMP_LISTCOMP:
3801 VISIT(c, expr, elt);
3802 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3803 break;
3804 case COMP_SETCOMP:
3805 VISIT(c, expr, elt);
3806 ADDOP_I(c, SET_ADD, gen_index + 1);
3807 break;
3808 case COMP_DICTCOMP:
3809 /* With 'd[k] = v', v is evaluated before k, so we do
3810 the same. */
3811 VISIT(c, expr, val);
3812 VISIT(c, expr, elt);
3813 ADDOP_I(c, MAP_ADD, gen_index + 1);
3814 break;
3815 default:
3816 return 0;
3817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 compiler_use_next_block(c, skip);
3820 }
3821 compiler_use_next_block(c, if_cleanup);
3822 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3823 compiler_use_next_block(c, anchor);
3824
3825 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826}
3827
3828static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003829compiler_async_comprehension_generator(struct compiler *c,
3830 asdl_seq *generators, int gen_index,
3831 expr_ty elt, expr_ty val, int type)
3832{
3833 _Py_IDENTIFIER(StopAsyncIteration);
3834
3835 comprehension_ty gen;
3836 basicblock *anchor, *skip, *if_cleanup, *try,
3837 *after_try, *except, *try_cleanup;
3838 Py_ssize_t i, n;
3839
3840 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3841 if (stop_aiter_error == NULL) {
3842 return 0;
3843 }
3844
3845 try = compiler_new_block(c);
3846 after_try = compiler_new_block(c);
3847 try_cleanup = compiler_new_block(c);
3848 except = compiler_new_block(c);
3849 skip = compiler_new_block(c);
3850 if_cleanup = compiler_new_block(c);
3851 anchor = compiler_new_block(c);
3852
3853 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3854 try == NULL || after_try == NULL ||
3855 except == NULL || after_try == NULL) {
3856 return 0;
3857 }
3858
3859 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3860
3861 if (gen_index == 0) {
3862 /* Receive outermost iter as an implicit argument */
3863 c->u->u_argcount = 1;
3864 ADDOP_I(c, LOAD_FAST, 0);
3865 }
3866 else {
3867 /* Sub-iter - calculate on the fly */
3868 VISIT(c, expr, gen->iter);
3869 ADDOP(c, GET_AITER);
3870 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3871 ADDOP(c, YIELD_FROM);
3872 }
3873
3874 compiler_use_next_block(c, try);
3875
3876
3877 ADDOP_JREL(c, SETUP_EXCEPT, except);
3878 if (!compiler_push_fblock(c, EXCEPT, try))
3879 return 0;
3880
3881 ADDOP(c, GET_ANEXT);
3882 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3883 ADDOP(c, YIELD_FROM);
3884 VISIT(c, expr, gen->target);
3885 ADDOP(c, POP_BLOCK);
3886 compiler_pop_fblock(c, EXCEPT, try);
3887 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3888
3889
3890 compiler_use_next_block(c, except);
3891 ADDOP(c, DUP_TOP);
3892 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3893 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3894 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3895
3896 ADDOP(c, POP_TOP);
3897 ADDOP(c, POP_TOP);
3898 ADDOP(c, POP_TOP);
3899 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3900 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3901
3902
3903 compiler_use_next_block(c, try_cleanup);
3904 ADDOP(c, END_FINALLY);
3905
3906 compiler_use_next_block(c, after_try);
3907
3908 n = asdl_seq_LEN(gen->ifs);
3909 for (i = 0; i < n; i++) {
3910 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003911 if (!compiler_jump_if(c, e, if_cleanup, 0))
3912 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003913 NEXT_BLOCK(c);
3914 }
3915
3916 if (++gen_index < asdl_seq_LEN(generators))
3917 if (!compiler_comprehension_generator(c,
3918 generators, gen_index,
3919 elt, val, type))
3920 return 0;
3921
3922 /* only append after the last for generator */
3923 if (gen_index >= asdl_seq_LEN(generators)) {
3924 /* comprehension specific code */
3925 switch (type) {
3926 case COMP_GENEXP:
3927 VISIT(c, expr, elt);
3928 ADDOP(c, YIELD_VALUE);
3929 ADDOP(c, POP_TOP);
3930 break;
3931 case COMP_LISTCOMP:
3932 VISIT(c, expr, elt);
3933 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3934 break;
3935 case COMP_SETCOMP:
3936 VISIT(c, expr, elt);
3937 ADDOP_I(c, SET_ADD, gen_index + 1);
3938 break;
3939 case COMP_DICTCOMP:
3940 /* With 'd[k] = v', v is evaluated before k, so we do
3941 the same. */
3942 VISIT(c, expr, val);
3943 VISIT(c, expr, elt);
3944 ADDOP_I(c, MAP_ADD, gen_index + 1);
3945 break;
3946 default:
3947 return 0;
3948 }
3949
3950 compiler_use_next_block(c, skip);
3951 }
3952 compiler_use_next_block(c, if_cleanup);
3953 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3954 compiler_use_next_block(c, anchor);
3955 ADDOP(c, POP_TOP);
3956
3957 return 1;
3958}
3959
3960static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003961compiler_comprehension(struct compiler *c, expr_ty e, int type,
3962 identifier name, asdl_seq *generators, expr_ty elt,
3963 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003967 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968 int is_async_function = c->u->u_ste->ste_coroutine;
3969 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003970
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003971 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003972
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003973 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3974 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003975 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003977 }
3978
3979 is_async_generator = c->u->u_ste->ste_coroutine;
3980
3981 if (is_async_generator && !is_async_function) {
3982 if (e->lineno > c->u->u_lineno) {
3983 c->u->u_lineno = e->lineno;
3984 c->u->u_lineno_set = 0;
3985 }
3986 compiler_error(c, "asynchronous comprehension outside of "
3987 "an asynchronous function");
3988 goto error_in_scope;
3989 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 if (type != COMP_GENEXP) {
3992 int op;
3993 switch (type) {
3994 case COMP_LISTCOMP:
3995 op = BUILD_LIST;
3996 break;
3997 case COMP_SETCOMP:
3998 op = BUILD_SET;
3999 break;
4000 case COMP_DICTCOMP:
4001 op = BUILD_MAP;
4002 break;
4003 default:
4004 PyErr_Format(PyExc_SystemError,
4005 "unknown comprehension type %d", type);
4006 goto error_in_scope;
4007 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 ADDOP_I(c, op, 0);
4010 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 if (!compiler_comprehension_generator(c, generators, 0, elt,
4013 val, type))
4014 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 if (type != COMP_GENEXP) {
4017 ADDOP(c, RETURN_VALUE);
4018 }
4019
4020 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004021 qualname = c->u->u_qualname;
4022 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004024 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 goto error;
4026
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004027 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004029 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 Py_DECREF(co);
4031
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004032 VISIT(c, expr, outermost->iter);
4033
4034 if (outermost->is_async) {
4035 ADDOP(c, GET_AITER);
4036 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4037 ADDOP(c, YIELD_FROM);
4038 } else {
4039 ADDOP(c, GET_ITER);
4040 }
4041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004043
4044 if (is_async_generator && type != COMP_GENEXP) {
4045 ADDOP(c, GET_AWAITABLE);
4046 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4047 ADDOP(c, YIELD_FROM);
4048 }
4049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004051error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004053error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004054 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 Py_XDECREF(co);
4056 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004057}
4058
4059static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004060compiler_genexp(struct compiler *c, expr_ty e)
4061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 static identifier name;
4063 if (!name) {
4064 name = PyUnicode_FromString("<genexpr>");
4065 if (!name)
4066 return 0;
4067 }
4068 assert(e->kind == GeneratorExp_kind);
4069 return compiler_comprehension(c, e, COMP_GENEXP, name,
4070 e->v.GeneratorExp.generators,
4071 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072}
4073
4074static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004075compiler_listcomp(struct compiler *c, expr_ty e)
4076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 static identifier name;
4078 if (!name) {
4079 name = PyUnicode_FromString("<listcomp>");
4080 if (!name)
4081 return 0;
4082 }
4083 assert(e->kind == ListComp_kind);
4084 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4085 e->v.ListComp.generators,
4086 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004087}
4088
4089static int
4090compiler_setcomp(struct compiler *c, expr_ty e)
4091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 static identifier name;
4093 if (!name) {
4094 name = PyUnicode_FromString("<setcomp>");
4095 if (!name)
4096 return 0;
4097 }
4098 assert(e->kind == SetComp_kind);
4099 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4100 e->v.SetComp.generators,
4101 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004102}
4103
4104
4105static int
4106compiler_dictcomp(struct compiler *c, expr_ty e)
4107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 static identifier name;
4109 if (!name) {
4110 name = PyUnicode_FromString("<dictcomp>");
4111 if (!name)
4112 return 0;
4113 }
4114 assert(e->kind == DictComp_kind);
4115 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4116 e->v.DictComp.generators,
4117 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004118}
4119
4120
4121static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122compiler_visit_keyword(struct compiler *c, keyword_ty k)
4123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 VISIT(c, expr, k->value);
4125 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126}
4127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129 whether they are true or false.
4130
4131 Return values: 1 for true, 0 for false, -1 for non-constant.
4132 */
4133
4134static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004135expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004137 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 switch (e->kind) {
4139 case Ellipsis_kind:
4140 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004141 case Constant_kind:
4142 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 case Num_kind:
4144 return PyObject_IsTrue(e->v.Num.n);
4145 case Str_kind:
4146 return PyObject_IsTrue(e->v.Str.s);
4147 case Name_kind:
4148 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004149 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004150 if (id && strcmp(id, "__debug__") == 0)
4151 return !c->c_optimize;
4152 return -1;
4153 case NameConstant_kind: {
4154 PyObject *o = e->v.NameConstant.value;
4155 if (o == Py_None)
4156 return 0;
4157 else if (o == Py_True)
4158 return 1;
4159 else if (o == Py_False)
4160 return 0;
4161 }
Stefan Krahf432a322017-08-21 13:09:59 +02004162 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 default:
4164 return -1;
4165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166}
4167
Yury Selivanov75445082015-05-11 22:57:16 -04004168
4169/*
4170 Implements the async with statement.
4171
4172 The semantics outlined in that PEP are as follows:
4173
4174 async with EXPR as VAR:
4175 BLOCK
4176
4177 It is implemented roughly as:
4178
4179 context = EXPR
4180 exit = context.__aexit__ # not calling it
4181 value = await context.__aenter__()
4182 try:
4183 VAR = value # if VAR present in the syntax
4184 BLOCK
4185 finally:
4186 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004187 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004188 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004189 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004190 if not (await exit(*exc)):
4191 raise
4192 */
4193static int
4194compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4195{
4196 basicblock *block, *finally;
4197 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4198
4199 assert(s->kind == AsyncWith_kind);
4200
4201 block = compiler_new_block(c);
4202 finally = compiler_new_block(c);
4203 if (!block || !finally)
4204 return 0;
4205
4206 /* Evaluate EXPR */
4207 VISIT(c, expr, item->context_expr);
4208
4209 ADDOP(c, BEFORE_ASYNC_WITH);
4210 ADDOP(c, GET_AWAITABLE);
4211 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4212 ADDOP(c, YIELD_FROM);
4213
4214 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4215
4216 /* SETUP_ASYNC_WITH pushes a finally block. */
4217 compiler_use_next_block(c, block);
4218 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4219 return 0;
4220 }
4221
4222 if (item->optional_vars) {
4223 VISIT(c, expr, item->optional_vars);
4224 }
4225 else {
4226 /* Discard result from context.__aenter__() */
4227 ADDOP(c, POP_TOP);
4228 }
4229
4230 pos++;
4231 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4232 /* BLOCK code */
4233 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4234 else if (!compiler_async_with(c, s, pos))
4235 return 0;
4236
4237 /* End of try block; start the finally block */
4238 ADDOP(c, POP_BLOCK);
4239 compiler_pop_fblock(c, FINALLY_TRY, block);
4240
4241 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4242 compiler_use_next_block(c, finally);
4243 if (!compiler_push_fblock(c, FINALLY_END, finally))
4244 return 0;
4245
4246 /* Finally block starts; context.__exit__ is on the stack under
4247 the exception or return information. Just issue our magic
4248 opcode. */
4249 ADDOP(c, WITH_CLEANUP_START);
4250
4251 ADDOP(c, GET_AWAITABLE);
4252 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4253 ADDOP(c, YIELD_FROM);
4254
4255 ADDOP(c, WITH_CLEANUP_FINISH);
4256
4257 /* Finally block ends. */
4258 ADDOP(c, END_FINALLY);
4259 compiler_pop_fblock(c, FINALLY_END, finally);
4260 return 1;
4261}
4262
4263
Guido van Rossumc2e20742006-02-27 22:32:47 +00004264/*
4265 Implements the with statement from PEP 343.
4266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004268
4269 with EXPR as VAR:
4270 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271
Guido van Rossumc2e20742006-02-27 22:32:47 +00004272 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273
Thomas Wouters477c8d52006-05-27 19:21:47 +00004274 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004275 exit = context.__exit__ # not calling it
4276 value = context.__enter__()
4277 try:
4278 VAR = value # if VAR present in the syntax
4279 BLOCK
4280 finally:
4281 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004282 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004283 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004284 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004285 exit(*exc)
4286 */
4287static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004288compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004289{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004290 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004291 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004292
4293 assert(s->kind == With_kind);
4294
Guido van Rossumc2e20742006-02-27 22:32:47 +00004295 block = compiler_new_block(c);
4296 finally = compiler_new_block(c);
4297 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004298 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004299
Thomas Wouters477c8d52006-05-27 19:21:47 +00004300 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004301 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004302 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004303
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004304 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004305 compiler_use_next_block(c, block);
4306 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004307 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004308 }
4309
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004310 if (item->optional_vars) {
4311 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004312 }
4313 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004315 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004316 }
4317
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004318 pos++;
4319 if (pos == asdl_seq_LEN(s->v.With.items))
4320 /* BLOCK code */
4321 VISIT_SEQ(c, stmt, s->v.With.body)
4322 else if (!compiler_with(c, s, pos))
4323 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004324
4325 /* End of try block; start the finally block */
4326 ADDOP(c, POP_BLOCK);
4327 compiler_pop_fblock(c, FINALLY_TRY, block);
4328
4329 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4330 compiler_use_next_block(c, finally);
4331 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004332 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004333
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004334 /* Finally block starts; context.__exit__ is on the stack under
4335 the exception or return information. Just issue our magic
4336 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004337 ADDOP(c, WITH_CLEANUP_START);
4338 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004339
4340 /* Finally block ends. */
4341 ADDOP(c, END_FINALLY);
4342 compiler_pop_fblock(c, FINALLY_END, finally);
4343 return 1;
4344}
4345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346static int
4347compiler_visit_expr(struct compiler *c, expr_ty e)
4348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 /* If expr e has a different line number than the last expr/stmt,
4350 set a new line number for the next instruction.
4351 */
4352 if (e->lineno > c->u->u_lineno) {
4353 c->u->u_lineno = e->lineno;
4354 c->u->u_lineno_set = 0;
4355 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004356 /* Updating the column offset is always harmless. */
4357 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 switch (e->kind) {
4359 case BoolOp_kind:
4360 return compiler_boolop(c, e);
4361 case BinOp_kind:
4362 VISIT(c, expr, e->v.BinOp.left);
4363 VISIT(c, expr, e->v.BinOp.right);
4364 ADDOP(c, binop(c, e->v.BinOp.op));
4365 break;
4366 case UnaryOp_kind:
4367 VISIT(c, expr, e->v.UnaryOp.operand);
4368 ADDOP(c, unaryop(e->v.UnaryOp.op));
4369 break;
4370 case Lambda_kind:
4371 return compiler_lambda(c, e);
4372 case IfExp_kind:
4373 return compiler_ifexp(c, e);
4374 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004375 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004377 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 case GeneratorExp_kind:
4379 return compiler_genexp(c, e);
4380 case ListComp_kind:
4381 return compiler_listcomp(c, e);
4382 case SetComp_kind:
4383 return compiler_setcomp(c, e);
4384 case DictComp_kind:
4385 return compiler_dictcomp(c, e);
4386 case Yield_kind:
4387 if (c->u->u_ste->ste_type != FunctionBlock)
4388 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004389 if (e->v.Yield.value) {
4390 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 }
4392 else {
4393 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4394 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004395 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004397 case YieldFrom_kind:
4398 if (c->u->u_ste->ste_type != FunctionBlock)
4399 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004400
4401 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4402 return compiler_error(c, "'yield from' inside async function");
4403
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004404 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004405 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004406 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4407 ADDOP(c, YIELD_FROM);
4408 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004409 case Await_kind:
4410 if (c->u->u_ste->ste_type != FunctionBlock)
4411 return compiler_error(c, "'await' outside function");
4412
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004413 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4414 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004415 return compiler_error(c, "'await' outside async function");
4416
4417 VISIT(c, expr, e->v.Await.value);
4418 ADDOP(c, GET_AWAITABLE);
4419 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4420 ADDOP(c, YIELD_FROM);
4421 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 case Compare_kind:
4423 return compiler_compare(c, e);
4424 case Call_kind:
4425 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004426 case Constant_kind:
4427 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4428 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 case Num_kind:
4430 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4431 break;
4432 case Str_kind:
4433 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4434 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004435 case JoinedStr_kind:
4436 return compiler_joined_str(c, e);
4437 case FormattedValue_kind:
4438 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 case Bytes_kind:
4440 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4441 break;
4442 case Ellipsis_kind:
4443 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4444 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004445 case NameConstant_kind:
4446 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4447 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* The following exprs can be assignment targets. */
4449 case Attribute_kind:
4450 if (e->v.Attribute.ctx != AugStore)
4451 VISIT(c, expr, e->v.Attribute.value);
4452 switch (e->v.Attribute.ctx) {
4453 case AugLoad:
4454 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004455 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 case Load:
4457 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4458 break;
4459 case AugStore:
4460 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004461 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 case Store:
4463 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4464 break;
4465 case Del:
4466 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4467 break;
4468 case Param:
4469 default:
4470 PyErr_SetString(PyExc_SystemError,
4471 "param invalid in attribute expression");
4472 return 0;
4473 }
4474 break;
4475 case Subscript_kind:
4476 switch (e->v.Subscript.ctx) {
4477 case AugLoad:
4478 VISIT(c, expr, e->v.Subscript.value);
4479 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4480 break;
4481 case Load:
4482 VISIT(c, expr, e->v.Subscript.value);
4483 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4484 break;
4485 case AugStore:
4486 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4487 break;
4488 case Store:
4489 VISIT(c, expr, e->v.Subscript.value);
4490 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4491 break;
4492 case Del:
4493 VISIT(c, expr, e->v.Subscript.value);
4494 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4495 break;
4496 case Param:
4497 default:
4498 PyErr_SetString(PyExc_SystemError,
4499 "param invalid in subscript expression");
4500 return 0;
4501 }
4502 break;
4503 case Starred_kind:
4504 switch (e->v.Starred.ctx) {
4505 case Store:
4506 /* In all legitimate cases, the Starred node was already replaced
4507 * by compiler_list/compiler_tuple. XXX: is that okay? */
4508 return compiler_error(c,
4509 "starred assignment target must be in a list or tuple");
4510 default:
4511 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004512 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 }
4514 break;
4515 case Name_kind:
4516 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4517 /* child nodes of List and Tuple will have expr_context set */
4518 case List_kind:
4519 return compiler_list(c, e);
4520 case Tuple_kind:
4521 return compiler_tuple(c, e);
4522 }
4523 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004524}
4525
4526static int
4527compiler_augassign(struct compiler *c, stmt_ty s)
4528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 expr_ty e = s->v.AugAssign.target;
4530 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 switch (e->kind) {
4535 case Attribute_kind:
4536 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4537 AugLoad, e->lineno, e->col_offset, c->c_arena);
4538 if (auge == NULL)
4539 return 0;
4540 VISIT(c, expr, auge);
4541 VISIT(c, expr, s->v.AugAssign.value);
4542 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4543 auge->v.Attribute.ctx = AugStore;
4544 VISIT(c, expr, auge);
4545 break;
4546 case Subscript_kind:
4547 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4548 AugLoad, e->lineno, e->col_offset, c->c_arena);
4549 if (auge == NULL)
4550 return 0;
4551 VISIT(c, expr, auge);
4552 VISIT(c, expr, s->v.AugAssign.value);
4553 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4554 auge->v.Subscript.ctx = AugStore;
4555 VISIT(c, expr, auge);
4556 break;
4557 case Name_kind:
4558 if (!compiler_nameop(c, e->v.Name.id, Load))
4559 return 0;
4560 VISIT(c, expr, s->v.AugAssign.value);
4561 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4562 return compiler_nameop(c, e->v.Name.id, Store);
4563 default:
4564 PyErr_Format(PyExc_SystemError,
4565 "invalid node type (%d) for augmented assignment",
4566 e->kind);
4567 return 0;
4568 }
4569 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004570}
4571
4572static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004573check_ann_expr(struct compiler *c, expr_ty e)
4574{
4575 VISIT(c, expr, e);
4576 ADDOP(c, POP_TOP);
4577 return 1;
4578}
4579
4580static int
4581check_annotation(struct compiler *c, stmt_ty s)
4582{
4583 /* Annotations are only evaluated in a module or class. */
4584 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4585 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4586 return check_ann_expr(c, s->v.AnnAssign.annotation);
4587 }
4588 return 1;
4589}
4590
4591static int
4592check_ann_slice(struct compiler *c, slice_ty sl)
4593{
4594 switch(sl->kind) {
4595 case Index_kind:
4596 return check_ann_expr(c, sl->v.Index.value);
4597 case Slice_kind:
4598 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4599 return 0;
4600 }
4601 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4602 return 0;
4603 }
4604 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4605 return 0;
4606 }
4607 break;
4608 default:
4609 PyErr_SetString(PyExc_SystemError,
4610 "unexpected slice kind");
4611 return 0;
4612 }
4613 return 1;
4614}
4615
4616static int
4617check_ann_subscr(struct compiler *c, slice_ty sl)
4618{
4619 /* We check that everything in a subscript is defined at runtime. */
4620 Py_ssize_t i, n;
4621
4622 switch (sl->kind) {
4623 case Index_kind:
4624 case Slice_kind:
4625 if (!check_ann_slice(c, sl)) {
4626 return 0;
4627 }
4628 break;
4629 case ExtSlice_kind:
4630 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4631 for (i = 0; i < n; i++) {
4632 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4633 switch (subsl->kind) {
4634 case Index_kind:
4635 case Slice_kind:
4636 if (!check_ann_slice(c, subsl)) {
4637 return 0;
4638 }
4639 break;
4640 case ExtSlice_kind:
4641 default:
4642 PyErr_SetString(PyExc_SystemError,
4643 "extended slice invalid in nested slice");
4644 return 0;
4645 }
4646 }
4647 break;
4648 default:
4649 PyErr_Format(PyExc_SystemError,
4650 "invalid subscript kind %d", sl->kind);
4651 return 0;
4652 }
4653 return 1;
4654}
4655
4656static int
4657compiler_annassign(struct compiler *c, stmt_ty s)
4658{
4659 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004660 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004661
4662 assert(s->kind == AnnAssign_kind);
4663
4664 /* We perform the actual assignment first. */
4665 if (s->v.AnnAssign.value) {
4666 VISIT(c, expr, s->v.AnnAssign.value);
4667 VISIT(c, expr, targ);
4668 }
4669 switch (targ->kind) {
4670 case Name_kind:
4671 /* If we have a simple name in a module or class, store annotation. */
4672 if (s->v.AnnAssign.simple &&
4673 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4674 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004675 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4676 if (!mangled) {
4677 return 0;
4678 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004679 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004680 /* ADDOP_N decrefs its argument */
4681 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004682 }
4683 break;
4684 case Attribute_kind:
4685 if (!s->v.AnnAssign.value &&
4686 !check_ann_expr(c, targ->v.Attribute.value)) {
4687 return 0;
4688 }
4689 break;
4690 case Subscript_kind:
4691 if (!s->v.AnnAssign.value &&
4692 (!check_ann_expr(c, targ->v.Subscript.value) ||
4693 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4694 return 0;
4695 }
4696 break;
4697 default:
4698 PyErr_Format(PyExc_SystemError,
4699 "invalid node type (%d) for annotated assignment",
4700 targ->kind);
4701 return 0;
4702 }
4703 /* Annotation is evaluated last. */
4704 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4705 return 0;
4706 }
4707 return 1;
4708}
4709
4710static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 struct fblockinfo *f;
4714 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004715 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 "too many statically nested blocks");
4717 return 0;
4718 }
4719 f = &c->u->u_fblock[c->u->u_nfblocks++];
4720 f->fb_type = t;
4721 f->fb_block = b;
4722 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004723}
4724
4725static void
4726compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 struct compiler_unit *u = c->u;
4729 assert(u->u_nfblocks > 0);
4730 u->u_nfblocks--;
4731 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4732 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004733}
4734
Thomas Wouters89f507f2006-12-13 04:49:30 +00004735static int
4736compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 int i;
4738 struct compiler_unit *u = c->u;
4739 for (i = 0; i < u->u_nfblocks; ++i) {
4740 if (u->u_fblock[i].fb_type == LOOP)
4741 return 1;
4742 }
4743 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004744}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745/* Raises a SyntaxError and returns 0.
4746 If something goes wrong, a different exception may be raised.
4747*/
4748
4749static int
4750compiler_error(struct compiler *c, const char *errstr)
4751{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004752 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004754
Victor Stinner14e461d2013-08-26 22:28:21 +02004755 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 if (!loc) {
4757 Py_INCREF(Py_None);
4758 loc = Py_None;
4759 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004760 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004761 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (!u)
4763 goto exit;
4764 v = Py_BuildValue("(zO)", errstr, u);
4765 if (!v)
4766 goto exit;
4767 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004768 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 Py_DECREF(loc);
4770 Py_XDECREF(u);
4771 Py_XDECREF(v);
4772 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773}
4774
4775static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776compiler_handle_subscr(struct compiler *c, const char *kind,
4777 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 /* XXX this code is duplicated */
4782 switch (ctx) {
4783 case AugLoad: /* fall through to Load */
4784 case Load: op = BINARY_SUBSCR; break;
4785 case AugStore:/* fall through to Store */
4786 case Store: op = STORE_SUBSCR; break;
4787 case Del: op = DELETE_SUBSCR; break;
4788 case Param:
4789 PyErr_Format(PyExc_SystemError,
4790 "invalid %s kind %d in subscript\n",
4791 kind, ctx);
4792 return 0;
4793 }
4794 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004795 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 }
4797 else if (ctx == AugStore) {
4798 ADDOP(c, ROT_THREE);
4799 }
4800 ADDOP(c, op);
4801 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802}
4803
4804static int
4805compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 int n = 2;
4808 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 /* only handles the cases where BUILD_SLICE is emitted */
4811 if (s->v.Slice.lower) {
4812 VISIT(c, expr, s->v.Slice.lower);
4813 }
4814 else {
4815 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 if (s->v.Slice.upper) {
4819 VISIT(c, expr, s->v.Slice.upper);
4820 }
4821 else {
4822 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4823 }
4824
4825 if (s->v.Slice.step) {
4826 n++;
4827 VISIT(c, expr, s->v.Slice.step);
4828 }
4829 ADDOP_I(c, BUILD_SLICE, n);
4830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831}
4832
4833static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4835 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 switch (s->kind) {
4838 case Slice_kind:
4839 return compiler_slice(c, s, ctx);
4840 case Index_kind:
4841 VISIT(c, expr, s->v.Index.value);
4842 break;
4843 case ExtSlice_kind:
4844 default:
4845 PyErr_SetString(PyExc_SystemError,
4846 "extended slice invalid in nested slice");
4847 return 0;
4848 }
4849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004850}
4851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004852static int
4853compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 char * kindname = NULL;
4856 switch (s->kind) {
4857 case Index_kind:
4858 kindname = "index";
4859 if (ctx != AugStore) {
4860 VISIT(c, expr, s->v.Index.value);
4861 }
4862 break;
4863 case Slice_kind:
4864 kindname = "slice";
4865 if (ctx != AugStore) {
4866 if (!compiler_slice(c, s, ctx))
4867 return 0;
4868 }
4869 break;
4870 case ExtSlice_kind:
4871 kindname = "extended slice";
4872 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004873 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 for (i = 0; i < n; i++) {
4875 slice_ty sub = (slice_ty)asdl_seq_GET(
4876 s->v.ExtSlice.dims, i);
4877 if (!compiler_visit_nested_slice(c, sub, ctx))
4878 return 0;
4879 }
4880 ADDOP_I(c, BUILD_TUPLE, n);
4881 }
4882 break;
4883 default:
4884 PyErr_Format(PyExc_SystemError,
4885 "invalid subscript kind %d", s->kind);
4886 return 0;
4887 }
4888 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004889}
4890
Thomas Wouters89f507f2006-12-13 04:49:30 +00004891/* End of the compiler section, beginning of the assembler section */
4892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893/* do depth-first search of basic block graph, starting with block.
4894 post records the block indices in post-order.
4895
4896 XXX must handle implicit jumps from one block to next
4897*/
4898
Thomas Wouters89f507f2006-12-13 04:49:30 +00004899struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 PyObject *a_bytecode; /* string containing bytecode */
4901 int a_offset; /* offset into bytecode */
4902 int a_nblocks; /* number of reachable blocks */
4903 basicblock **a_postorder; /* list of blocks in dfs postorder */
4904 PyObject *a_lnotab; /* string containing lnotab */
4905 int a_lnotab_off; /* offset into lnotab */
4906 int a_lineno; /* last lineno of emitted instruction */
4907 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004908};
4909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004910static void
4911dfs(struct compiler *c, basicblock *b, struct assembler *a)
4912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 int i;
4914 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 if (b->b_seen)
4917 return;
4918 b->b_seen = 1;
4919 if (b->b_next != NULL)
4920 dfs(c, b->b_next, a);
4921 for (i = 0; i < b->b_iused; i++) {
4922 instr = &b->b_instr[i];
4923 if (instr->i_jrel || instr->i_jabs)
4924 dfs(c, instr->i_target, a);
4925 }
4926 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004927}
4928
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004930stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4931{
Larry Hastings3a907972013-11-23 14:49:22 -08004932 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 struct instr *instr;
4934 if (b->b_seen || b->b_startdepth >= depth)
4935 return maxdepth;
4936 b->b_seen = 1;
4937 b->b_startdepth = depth;
4938 for (i = 0; i < b->b_iused; i++) {
4939 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004940 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4941 if (effect == PY_INVALID_STACK_EFFECT) {
4942 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4943 Py_FatalError("PyCompile_OpcodeStackEffect()");
4944 }
4945 depth += effect;
4946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 if (depth > maxdepth)
4948 maxdepth = depth;
4949 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4950 if (instr->i_jrel || instr->i_jabs) {
4951 target_depth = depth;
4952 if (instr->i_opcode == FOR_ITER) {
4953 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004954 }
4955 else if (instr->i_opcode == SETUP_FINALLY ||
4956 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 target_depth = depth+3;
4958 if (target_depth > maxdepth)
4959 maxdepth = target_depth;
4960 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004961 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4962 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4963 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 maxdepth = stackdepth_walk(c, instr->i_target,
4965 target_depth, maxdepth);
4966 if (instr->i_opcode == JUMP_ABSOLUTE ||
4967 instr->i_opcode == JUMP_FORWARD) {
4968 goto out; /* remaining code is dead */
4969 }
4970 }
4971 }
4972 if (b->b_next)
4973 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004974out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 b->b_seen = 0;
4976 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004977}
4978
4979/* Find the flow path that needs the largest stack. We assume that
4980 * cycles in the flow graph have no net effect on the stack depth.
4981 */
4982static int
4983stackdepth(struct compiler *c)
4984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 basicblock *b, *entryblock;
4986 entryblock = NULL;
4987 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4988 b->b_seen = 0;
4989 b->b_startdepth = INT_MIN;
4990 entryblock = b;
4991 }
4992 if (!entryblock)
4993 return 0;
4994 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004995}
4996
4997static int
4998assemble_init(struct assembler *a, int nblocks, int firstlineno)
4999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 memset(a, 0, sizeof(struct assembler));
5001 a->a_lineno = firstlineno;
5002 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5003 if (!a->a_bytecode)
5004 return 0;
5005 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5006 if (!a->a_lnotab)
5007 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005008 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 PyErr_NoMemory();
5010 return 0;
5011 }
5012 a->a_postorder = (basicblock **)PyObject_Malloc(
5013 sizeof(basicblock *) * nblocks);
5014 if (!a->a_postorder) {
5015 PyErr_NoMemory();
5016 return 0;
5017 }
5018 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005019}
5020
5021static void
5022assemble_free(struct assembler *a)
5023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 Py_XDECREF(a->a_bytecode);
5025 Py_XDECREF(a->a_lnotab);
5026 if (a->a_postorder)
5027 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005028}
5029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005030static int
5031blocksize(basicblock *b)
5032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 int i;
5034 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005037 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005039}
5040
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005041/* Appends a pair to the end of the line number table, a_lnotab, representing
5042 the instruction's bytecode offset and line number. See
5043 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005044
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005045static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005046assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005049 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005051
Serhiy Storchakaab874002016-09-11 13:48:15 +03005052 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 if(d_bytecode == 0 && d_lineno == 0)
5058 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 if (d_bytecode > 255) {
5061 int j, nbytes, ncodes = d_bytecode / 255;
5062 nbytes = a->a_lnotab_off + 2 * ncodes;
5063 len = PyBytes_GET_SIZE(a->a_lnotab);
5064 if (nbytes >= len) {
5065 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5066 len = nbytes;
5067 else if (len <= INT_MAX / 2)
5068 len *= 2;
5069 else {
5070 PyErr_NoMemory();
5071 return 0;
5072 }
5073 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5074 return 0;
5075 }
5076 lnotab = (unsigned char *)
5077 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5078 for (j = 0; j < ncodes; j++) {
5079 *lnotab++ = 255;
5080 *lnotab++ = 0;
5081 }
5082 d_bytecode -= ncodes * 255;
5083 a->a_lnotab_off += ncodes * 2;
5084 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005085 assert(0 <= d_bytecode && d_bytecode <= 255);
5086
5087 if (d_lineno < -128 || 127 < d_lineno) {
5088 int j, nbytes, ncodes, k;
5089 if (d_lineno < 0) {
5090 k = -128;
5091 /* use division on positive numbers */
5092 ncodes = (-d_lineno) / 128;
5093 }
5094 else {
5095 k = 127;
5096 ncodes = d_lineno / 127;
5097 }
5098 d_lineno -= ncodes * k;
5099 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 nbytes = a->a_lnotab_off + 2 * ncodes;
5101 len = PyBytes_GET_SIZE(a->a_lnotab);
5102 if (nbytes >= len) {
5103 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5104 len = nbytes;
5105 else if (len <= INT_MAX / 2)
5106 len *= 2;
5107 else {
5108 PyErr_NoMemory();
5109 return 0;
5110 }
5111 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5112 return 0;
5113 }
5114 lnotab = (unsigned char *)
5115 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5116 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005117 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 d_bytecode = 0;
5119 for (j = 1; j < ncodes; j++) {
5120 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005121 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 a->a_lnotab_off += ncodes * 2;
5124 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005125 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 len = PyBytes_GET_SIZE(a->a_lnotab);
5128 if (a->a_lnotab_off + 2 >= len) {
5129 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5130 return 0;
5131 }
5132 lnotab = (unsigned char *)
5133 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 a->a_lnotab_off += 2;
5136 if (d_bytecode) {
5137 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005138 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 }
5140 else { /* First line of a block; def stmt, etc. */
5141 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005142 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 }
5144 a->a_lineno = i->i_lineno;
5145 a->a_lineno_off = a->a_offset;
5146 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005147}
5148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005149/* assemble_emit()
5150 Extend the bytecode with a new instruction.
5151 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005152*/
5153
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005154static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005155assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005156{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005157 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005159 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005160
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005161 arg = i->i_oparg;
5162 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 if (i->i_lineno && !assemble_lnotab(a, i))
5164 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005165 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 if (len > PY_SSIZE_T_MAX / 2)
5167 return 0;
5168 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5169 return 0;
5170 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005171 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005173 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005175}
5176
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005177static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005178assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005181 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 /* Compute the size of each block and fixup jump args.
5185 Replace block pointer with position in bytecode. */
5186 do {
5187 totsize = 0;
5188 for (i = a->a_nblocks - 1; i >= 0; i--) {
5189 b = a->a_postorder[i];
5190 bsize = blocksize(b);
5191 b->b_offset = totsize;
5192 totsize += bsize;
5193 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005194 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5196 bsize = b->b_offset;
5197 for (i = 0; i < b->b_iused; i++) {
5198 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005199 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 /* Relative jumps are computed relative to
5201 the instruction pointer after fetching
5202 the jump instruction.
5203 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005204 bsize += isize;
5205 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005207 if (instr->i_jrel) {
5208 instr->i_oparg -= bsize;
5209 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005210 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005211 if (instrsize(instr->i_oparg) != isize) {
5212 extended_arg_recompile = 1;
5213 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 }
5216 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 /* XXX: This is an awful hack that could hurt performance, but
5219 on the bright side it should work until we come up
5220 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 The issue is that in the first loop blocksize() is called
5223 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005224 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 So we loop until we stop seeing new EXTENDED_ARGs.
5228 The only EXTENDED_ARGs that could be popping up are
5229 ones in jump instructions. So this should converge
5230 fairly quickly.
5231 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005232 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005233}
5234
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005235static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005236dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005239 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 tuple = PyTuple_New(size);
5242 if (tuple == NULL)
5243 return NULL;
5244 while (PyDict_Next(dict, &pos, &k, &v)) {
5245 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005246 /* The keys of the dictionary are tuples. (see compiler_add_o
5247 * and _PyCode_ConstantKey). The object we want is always second,
5248 * though. */
5249 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 Py_INCREF(k);
5251 assert((i - offset) < size);
5252 assert((i - offset) >= 0);
5253 PyTuple_SET_ITEM(tuple, i - offset, k);
5254 }
5255 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005256}
5257
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005258static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005259compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005262 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005264 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 if (ste->ste_nested)
5266 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005267 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005269 if (!ste->ste_generator && ste->ste_coroutine)
5270 flags |= CO_COROUTINE;
5271 if (ste->ste_generator && ste->ste_coroutine)
5272 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 if (ste->ste_varargs)
5274 flags |= CO_VARARGS;
5275 if (ste->ste_varkeywords)
5276 flags |= CO_VARKEYWORDS;
5277 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 /* (Only) inherit compilerflags in PyCF_MASK */
5280 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005281
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005282 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5283 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5284 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005288}
5289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290static PyCodeObject *
5291makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 PyObject *tmp;
5294 PyCodeObject *co = NULL;
5295 PyObject *consts = NULL;
5296 PyObject *names = NULL;
5297 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 PyObject *name = NULL;
5299 PyObject *freevars = NULL;
5300 PyObject *cellvars = NULL;
5301 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005302 Py_ssize_t nlocals;
5303 int nlocals_int;
5304 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005305 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 tmp = dict_keys_inorder(c->u->u_consts, 0);
5308 if (!tmp)
5309 goto error;
5310 consts = PySequence_List(tmp); /* optimize_code requires a list */
5311 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 names = dict_keys_inorder(c->u->u_names, 0);
5314 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5315 if (!consts || !names || !varnames)
5316 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5319 if (!cellvars)
5320 goto error;
5321 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5322 if (!freevars)
5323 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005324
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005325 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005326 assert(nlocals < INT_MAX);
5327 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 flags = compute_code_flags(c);
5330 if (flags < 0)
5331 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5334 if (!bytecode)
5335 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5338 if (!tmp)
5339 goto error;
5340 Py_DECREF(consts);
5341 consts = tmp;
5342
Victor Stinnerf8e32212013-11-19 23:56:34 +01005343 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5344 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5345 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005346 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 bytecode, consts, names, varnames,
5348 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005349 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 c->u->u_firstlineno,
5351 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005352 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 Py_XDECREF(consts);
5354 Py_XDECREF(names);
5355 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 Py_XDECREF(name);
5357 Py_XDECREF(freevars);
5358 Py_XDECREF(cellvars);
5359 Py_XDECREF(bytecode);
5360 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005361}
5362
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005363
5364/* For debugging purposes only */
5365#if 0
5366static void
5367dump_instr(const struct instr *i)
5368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 const char *jrel = i->i_jrel ? "jrel " : "";
5370 const char *jabs = i->i_jabs ? "jabs " : "";
5371 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005374 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5378 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005379}
5380
5381static void
5382dump_basicblock(const basicblock *b)
5383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 const char *seen = b->b_seen ? "seen " : "";
5385 const char *b_return = b->b_return ? "return " : "";
5386 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5387 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5388 if (b->b_instr) {
5389 int i;
5390 for (i = 0; i < b->b_iused; i++) {
5391 fprintf(stderr, " [%02d] ", i);
5392 dump_instr(b->b_instr + i);
5393 }
5394 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005395}
5396#endif
5397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398static PyCodeObject *
5399assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 basicblock *b, *entryblock;
5402 struct assembler a;
5403 int i, j, nblocks;
5404 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 /* Make sure every block that falls off the end returns None.
5407 XXX NEXT_BLOCK() isn't quite right, because if the last
5408 block ends with a jump or return b_next shouldn't set.
5409 */
5410 if (!c->u->u_curblock->b_return) {
5411 NEXT_BLOCK(c);
5412 if (addNone)
5413 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5414 ADDOP(c, RETURN_VALUE);
5415 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 nblocks = 0;
5418 entryblock = NULL;
5419 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5420 nblocks++;
5421 entryblock = b;
5422 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 /* Set firstlineno if it wasn't explicitly set. */
5425 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005426 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5428 else
5429 c->u->u_firstlineno = 1;
5430 }
5431 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5432 goto error;
5433 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 /* Can't modify the bytecode after computing jump offsets. */
5436 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 /* Emit code in reverse postorder from dfs. */
5439 for (i = a.a_nblocks - 1; i >= 0; i--) {
5440 b = a.a_postorder[i];
5441 for (j = 0; j < b->b_iused; j++)
5442 if (!assemble_emit(&a, &b->b_instr[j]))
5443 goto error;
5444 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5447 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005448 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005452 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 assemble_free(&a);
5454 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005455}
Georg Brandl8334fd92010-12-04 10:26:46 +00005456
5457#undef PyAST_Compile
5458PyAPI_FUNC(PyCodeObject *)
5459PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5460 PyArena *arena)
5461{
5462 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5463}