blob: 18877d96da10bb636aa06abf6f1e13d8e107fc31 [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"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
67 unsigned b_seen : 1;
68 /* b_return is true if a RETURN_VALUE opcode is inserted. */
69 unsigned b_return : 1;
70 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
73 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020083enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
84 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020089 /* (optional) type-specific exit or cleanup block */
90 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040097 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040098 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010099 COMPILER_SCOPE_COMPREHENSION,
100};
101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000102/* The following items change on entry and exit of code blocks.
103 They must be saved and restored when returning to a block.
104*/
105struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400109 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100110 int u_scope_type;
111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* The following fields are dicts that map objects to
113 the index of them in co_XXX. The index is used as
114 the argument for opcodes that refer to those collections.
115 */
116 PyObject *u_consts; /* all constants */
117 PyObject *u_names; /* all names */
118 PyObject *u_varnames; /* local variables */
119 PyObject *u_cellvars; /* cell variables */
120 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Victor Stinnerf8e32212013-11-19 23:56:34 +0100124 Py_ssize_t u_argcount; /* number of arguments for block */
125 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 /* Pointer to the most recently allocated block. By following b_list
127 members, you can reach all early allocated blocks. */
128 basicblock *u_blocks;
129 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int u_nfblocks;
132 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 int u_firstlineno; /* the first lineno of the block */
135 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000136 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_lineno_set; /* boolean to indicate whether instr
138 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139};
140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000146
147Note that we don't track recursion levels during compilation - the
148task of detecting and rejecting excessive levels of nesting is
149handled by the symbol analysis pass.
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151*/
152
153struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200154 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 struct symtable *c_st;
156 PyFutureFeatures *c_future; /* pointer to module's __future__ */
157 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Georg Brandl8334fd92010-12-04 10:26:46 +0000159 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 int c_interactive; /* true if in interactive mode */
161 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
INADA Naokic2e16072018-11-26 21:23:22 +0900163 PyObject *c_const_cache; /* Python dict holding all constants,
164 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 struct compiler_unit *u; /* compiler state for current block */
166 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
167 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168};
169
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100170static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static void compiler_free(struct compiler *);
172static basicblock *compiler_new_block(struct compiler *);
173static int compiler_next_instr(struct compiler *, basicblock *);
174static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100175static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200178static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
180
181static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
182static int compiler_visit_stmt(struct compiler *, stmt_ty);
183static int compiler_visit_keyword(struct compiler *, keyword_ty);
184static int compiler_visit_expr(struct compiler *, expr_ty);
185static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700186static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200191static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500193static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400194static int compiler_async_with(struct compiler *, stmt_ty, int);
195static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100196static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400198 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500199static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400200static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000201
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700202static int compiler_sync_comprehension_generator(
203 struct compiler *c,
204 asdl_seq *generators, int gen_index,
205 expr_ty elt, expr_ty val, int type);
206
207static int compiler_async_comprehension_generator(
208 struct compiler *c,
209 asdl_seq *generators, int gen_index,
210 expr_ty elt, expr_ty val, int type);
211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000213static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400215#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Name mangling: __private becomes _classname__private.
221 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200222 PyObject *result;
223 size_t nlen, plen, ipriv;
224 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200226 PyUnicode_READ_CHAR(ident, 0) != '_' ||
227 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_INCREF(ident);
229 return ident;
230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200231 nlen = PyUnicode_GET_LENGTH(ident);
232 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 The only time a name with a dot can occur is when
236 we are compiling an import statement that has a
237 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 TODO(jhylton): Decide whether we want to support
240 mangling of the module name, e.g. __M.X.
241 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
243 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
244 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle __whatever__ */
247 }
248 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 ipriv = 0;
250 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
251 ipriv++;
252 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_INCREF(ident);
254 return ident; /* Don't mangle if class is just underscores */
255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Antoine Pitrou55bff892013-04-06 21:21:04 +0200258 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
259 PyErr_SetString(PyExc_OverflowError,
260 "private identifier too large to be mangled");
261 return NULL;
262 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
265 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
266 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
267
268 result = PyUnicode_New(1 + nlen + plen, maxchar);
269 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
272 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200273 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
274 Py_DECREF(result);
275 return NULL;
276 }
277 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
278 Py_DECREF(result);
279 return NULL;
280 }
Victor Stinner8f825062012-04-27 13:55:39 +0200281 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000283}
284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285static int
286compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000289
INADA Naokic2e16072018-11-26 21:23:22 +0900290 c->c_const_cache = PyDict_New();
291 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900293 }
294
295 c->c_stack = PyList_New(0);
296 if (!c->c_stack) {
297 Py_CLEAR(c->c_const_cache);
298 return 0;
299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302}
303
304PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200305PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
306 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 struct compiler c;
309 PyCodeObject *co = NULL;
310 PyCompilerFlags local_flags;
311 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!__doc__) {
314 __doc__ = PyUnicode_InternFromString("__doc__");
315 if (!__doc__)
316 return NULL;
317 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000318 if (!__annotations__) {
319 __annotations__ = PyUnicode_InternFromString("__annotations__");
320 if (!__annotations__)
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!compiler_init(&c))
324 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 c.c_filename = filename;
327 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200328 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (c.c_future == NULL)
330 goto finally;
331 if (!flags) {
332 local_flags.cf_flags = 0;
333 flags = &local_flags;
334 }
335 merged = c.c_future->ff_features | flags->cf_flags;
336 c.c_future->ff_features = merged;
337 flags->cf_flags = merged;
338 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000339 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200342 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900343 goto finally;
344 }
345
Victor Stinner14e461d2013-08-26 22:28:21 +0200346 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (c.c_st == NULL) {
348 if (!PyErr_Occurred())
349 PyErr_SetString(PyExc_SystemError, "no symtable");
350 goto finally;
351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Thomas Wouters1175c432006-02-27 22:49:54 +0000355 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 compiler_free(&c);
357 assert(co || PyErr_Occurred());
358 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359}
360
361PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200362PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
363 int optimize, PyArena *arena)
364{
365 PyObject *filename;
366 PyCodeObject *co;
367 filename = PyUnicode_DecodeFSDefault(filename_str);
368 if (filename == NULL)
369 return NULL;
370 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
371 Py_DECREF(filename);
372 return co;
373
374}
375
376PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377PyNode_Compile(struct _node *n, const char *filename)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyCodeObject *co = NULL;
380 mod_ty mod;
381 PyArena *arena = PyArena_New();
382 if (!arena)
383 return NULL;
384 mod = PyAST_FromNode(n, NULL, filename, arena);
385 if (mod)
386 co = PyAST_Compile(mod, filename, NULL, arena);
387 PyArena_Free(arena);
388 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000389}
390
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (c->c_st)
395 PySymtable_Free(c->c_st);
396 if (c->c_future)
397 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200398 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900399 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401}
402
Guido van Rossum79f25d91997-04-29 20:08:16 +0000403static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 Py_ssize_t i, n;
407 PyObject *v, *k;
408 PyObject *dict = PyDict_New();
409 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 n = PyList_Size(list);
412 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100413 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (!v) {
415 Py_DECREF(dict);
416 return NULL;
417 }
418 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300419 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_DECREF(v);
421 Py_DECREF(dict);
422 return NULL;
423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_DECREF(v);
425 }
426 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427}
428
429/* Return new dict containing names from src that match scope(s).
430
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000431src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433values are integers, starting at offset and increasing by one for
434each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435*/
436
437static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100438dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700440 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500442 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(offset >= 0);
445 if (dest == NULL)
446 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Meador Inge2ca63152012-07-18 14:20:11 -0500448 /* Sort the keys so that we have a deterministic order on the indexes
449 saved in the returned dictionary. These indexes are used as indexes
450 into the free and cell var storage. Therefore if they aren't
451 deterministic, then the generated bytecode is not deterministic.
452 */
453 sorted_keys = PyDict_Keys(src);
454 if (sorted_keys == NULL)
455 return NULL;
456 if (PyList_Sort(sorted_keys) != 0) {
457 Py_DECREF(sorted_keys);
458 return NULL;
459 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500460 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500461
462 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* XXX this should probably be a macro in symtable.h */
464 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500465 k = PyList_GET_ITEM(sorted_keys, key_i);
466 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 assert(PyLong_Check(v));
468 vi = PyLong_AS_LONG(v);
469 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300472 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500474 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_DECREF(dest);
476 return NULL;
477 }
478 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300479 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500480 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_DECREF(item);
482 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
484 }
485 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 }
487 }
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000490}
491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492static void
493compiler_unit_check(struct compiler_unit *u)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 basicblock *block;
496 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700497 assert((uintptr_t)block != 0xcbcbcbcbU);
498 assert((uintptr_t)block != 0xfbfbfbfbU);
499 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (block->b_instr != NULL) {
501 assert(block->b_ialloc > 0);
502 assert(block->b_iused > 0);
503 assert(block->b_ialloc >= block->b_iused);
504 }
505 else {
506 assert (block->b_iused == 0);
507 assert (block->b_ialloc == 0);
508 }
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510}
511
512static void
513compiler_unit_free(struct compiler_unit *u)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 compiler_unit_check(u);
518 b = u->u_blocks;
519 while (b != NULL) {
520 if (b->b_instr)
521 PyObject_Free((void *)b->b_instr);
522 next = b->b_list;
523 PyObject_Free((void *)b);
524 b = next;
525 }
526 Py_CLEAR(u->u_ste);
527 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400528 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 Py_CLEAR(u->u_consts);
530 Py_CLEAR(u->u_names);
531 Py_CLEAR(u->u_varnames);
532 Py_CLEAR(u->u_freevars);
533 Py_CLEAR(u->u_cellvars);
534 Py_CLEAR(u->u_private);
535 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100539compiler_enter_scope(struct compiler *c, identifier name,
540 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100543 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
546 struct compiler_unit));
547 if (!u) {
548 PyErr_NoMemory();
549 return 0;
550 }
551 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100552 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u->u_argcount = 0;
554 u->u_kwonlyargcount = 0;
555 u->u_ste = PySymtable_Lookup(c->c_st, key);
556 if (!u->u_ste) {
557 compiler_unit_free(u);
558 return 0;
559 }
560 Py_INCREF(name);
561 u->u_name = name;
562 u->u_varnames = list2dict(u->u_ste->ste_varnames);
563 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
564 if (!u->u_varnames || !u->u_cellvars) {
565 compiler_unit_free(u);
566 return 0;
567 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000569 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500570 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300571 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 int res;
573 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200574 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 name = _PyUnicode_FromId(&PyId___class__);
576 if (!name) {
577 compiler_unit_free(u);
578 return 0;
579 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 if (res < 0) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200588 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!u->u_freevars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_blocks = NULL;
595 u->u_nfblocks = 0;
596 u->u_firstlineno = lineno;
597 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000598 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_lineno_set = 0;
600 u->u_consts = PyDict_New();
601 if (!u->u_consts) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 u->u_names = PyDict_New();
606 if (!u->u_names) {
607 compiler_unit_free(u);
608 return 0;
609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Push the old compiler_unit on the stack. */
614 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400615 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
617 Py_XDECREF(capsule);
618 compiler_unit_free(u);
619 return 0;
620 }
621 Py_DECREF(capsule);
622 u->u_private = c->u->u_private;
623 Py_XINCREF(u->u_private);
624 }
625 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100628
629 block = compiler_new_block(c);
630 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100632 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400634 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
635 if (!compiler_set_qualname(c))
636 return 0;
637 }
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640}
641
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643compiler_exit_scope(struct compiler *c)
644{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100645 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 c->c_nestlevel--;
649 compiler_unit_free(c->u);
650 /* Restore c->u to the parent unit. */
651 n = PyList_GET_SIZE(c->c_stack) - 1;
652 if (n >= 0) {
653 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400654 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 assert(c->u);
656 /* we are deleting from a list so this really shouldn't fail */
657 if (PySequence_DelItem(c->c_stack, n) < 0)
658 Py_FatalError("compiler_exit_scope()");
659 compiler_unit_check(c->u);
660 }
661 else
662 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666static int
667compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 _Py_static_string(dot_locals, ".<locals>");
671 Py_ssize_t stack_size;
672 struct compiler_unit *u = c->u;
673 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400677 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 if (stack_size > 1) {
679 int scope, force_global = 0;
680 struct compiler_unit *parent;
681 PyObject *mangled, *capsule;
682
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400683 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(parent);
686
Yury Selivanov75445082015-05-11 22:57:16 -0400687 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 assert(u->u_name);
691 mangled = _Py_Mangle(parent->u_private, u->u_name);
692 if (!mangled)
693 return 0;
694 scope = PyST_GetScope(parent->u_ste, mangled);
695 Py_DECREF(mangled);
696 assert(scope != GLOBAL_IMPLICIT);
697 if (scope == GLOBAL_EXPLICIT)
698 force_global = 1;
699 }
700
701 if (!force_global) {
702 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400703 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
705 dot_locals_str = _PyUnicode_FromId(&dot_locals);
706 if (dot_locals_str == NULL)
707 return 0;
708 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
709 if (base == NULL)
710 return 0;
711 }
712 else {
713 Py_INCREF(parent->u_qualname);
714 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400715 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100716 }
717 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 if (base != NULL) {
720 dot_str = _PyUnicode_FromId(&dot);
721 if (dot_str == NULL) {
722 Py_DECREF(base);
723 return 0;
724 }
725 name = PyUnicode_Concat(base, dot_str);
726 Py_DECREF(base);
727 if (name == NULL)
728 return 0;
729 PyUnicode_Append(&name, u->u_name);
730 if (name == NULL)
731 return 0;
732 }
733 else {
734 Py_INCREF(u->u_name);
735 name = u->u_name;
736 }
737 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100738
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400739 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740}
741
Eric V. Smith235a6f02015-09-19 14:51:32 -0400742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743/* Allocate a new block and return a pointer to it.
744 Returns NULL on error.
745*/
746
747static basicblock *
748compiler_new_block(struct compiler *c)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 basicblock *b;
751 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 u = c->u;
754 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
755 if (b == NULL) {
756 PyErr_NoMemory();
757 return NULL;
758 }
759 memset((void *)b, 0, sizeof(basicblock));
760 /* Extend the singly linked list of blocks with new block. */
761 b->b_list = u->u_blocks;
762 u->u_blocks = b;
763 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764}
765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767compiler_next_block(struct compiler *c)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 basicblock *block = compiler_new_block(c);
770 if (block == NULL)
771 return NULL;
772 c->u->u_curblock->b_next = block;
773 c->u->u_curblock = block;
774 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
777static basicblock *
778compiler_use_next_block(struct compiler *c, basicblock *block)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 assert(block != NULL);
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786/* Returns the offset of the next instruction in the current block's
787 b_instr array. Resizes the b_instr as necessary.
788 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790
791static int
792compiler_next_instr(struct compiler *c, basicblock *b)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(b != NULL);
795 if (b->b_instr == NULL) {
796 b->b_instr = (struct instr *)PyObject_Malloc(
797 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
798 if (b->b_instr == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 b->b_ialloc = DEFAULT_BLOCK_SIZE;
803 memset((char *)b->b_instr, 0,
804 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
805 }
806 else if (b->b_iused == b->b_ialloc) {
807 struct instr *tmp;
808 size_t oldsize, newsize;
809 oldsize = b->b_ialloc * sizeof(struct instr);
810 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700812 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyErr_NoMemory();
814 return -1;
815 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (newsize == 0) {
818 PyErr_NoMemory();
819 return -1;
820 }
821 b->b_ialloc <<= 1;
822 tmp = (struct instr *)PyObject_Realloc(
823 (void *)b->b_instr, newsize);
824 if (tmp == NULL) {
825 PyErr_NoMemory();
826 return -1;
827 }
828 b->b_instr = tmp;
829 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
830 }
831 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832}
833
Christian Heimes2202f872008-02-06 14:31:34 +0000834/* Set the i_lineno member of the instruction at offset off if the
835 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836 already been set. If it has been set, the call has no effect.
837
Christian Heimes2202f872008-02-06 14:31:34 +0000838 The line number is reset in the following cases:
839 - when entering a new scope
840 - on each statement
841 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200842 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000843 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846static void
847compiler_set_lineno(struct compiler *c, int off)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 basicblock *b;
850 if (c->u->u_lineno_set)
851 return;
852 c->u->u_lineno_set = 1;
853 b = c->u->u_curblock;
854 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855}
856
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200857/* Return the stack effect of opcode with argument oparg.
858
859 Some opcodes have different stack effect when jump to the target and
860 when not jump. The 'jump' parameter specifies the case:
861
862 * 0 -- when not jump
863 * 1 -- when jump
864 * -1 -- maximal
865 */
866/* XXX Make the stack effect of WITH_CLEANUP_START and
867 WITH_CLEANUP_FINISH deterministic. */
868static int
869stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300872 case NOP:
873 case EXTENDED_ARG:
874 return 0;
875
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200876 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case POP_TOP:
878 return -1;
879 case ROT_TWO:
880 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200881 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return 0;
883 case DUP_TOP:
884 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000885 case DUP_TOP_TWO:
886 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case UNARY_POSITIVE:
890 case UNARY_NEGATIVE:
891 case UNARY_NOT:
892 case UNARY_INVERT:
893 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case SET_ADD:
896 case LIST_APPEND:
897 return -1;
898 case MAP_ADD:
899 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000900
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case BINARY_POWER:
903 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400904 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case BINARY_MODULO:
906 case BINARY_ADD:
907 case BINARY_SUBTRACT:
908 case BINARY_SUBSCR:
909 case BINARY_FLOOR_DIVIDE:
910 case BINARY_TRUE_DIVIDE:
911 return -1;
912 case INPLACE_FLOOR_DIVIDE:
913 case INPLACE_TRUE_DIVIDE:
914 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case INPLACE_ADD:
917 case INPLACE_SUBTRACT:
918 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400919 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case INPLACE_MODULO:
921 return -1;
922 case STORE_SUBSCR:
923 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case DELETE_SUBSCR:
925 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case BINARY_LSHIFT:
928 case BINARY_RSHIFT:
929 case BINARY_AND:
930 case BINARY_XOR:
931 case BINARY_OR:
932 return -1;
933 case INPLACE_POWER:
934 return -1;
935 case GET_ITER:
936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case PRINT_EXPR:
939 return -1;
940 case LOAD_BUILD_CLASS:
941 return 1;
942 case INPLACE_LSHIFT:
943 case INPLACE_RSHIFT:
944 case INPLACE_AND:
945 case INPLACE_XOR:
946 case INPLACE_OR:
947 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200950 /* 1 in the normal flow.
951 * Restore the stack position and push 6 values before jumping to
952 * the handler if an exception be raised. */
953 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400954 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400956 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200957 /* Pop a variable number of values pushed by WITH_CLEANUP_START
958 * + __exit__ or __aexit__. */
959 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case RETURN_VALUE:
961 return -1;
962 case IMPORT_STAR:
963 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700964 case SETUP_ANNOTATIONS:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case YIELD_VALUE:
967 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500968 case YIELD_FROM:
969 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case POP_BLOCK:
971 return 0;
972 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200973 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200975 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 /* Pop 6 values when an exception was raised. */
977 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case STORE_NAME:
980 return -1;
981 case DELETE_NAME:
982 return 0;
983 case UNPACK_SEQUENCE:
984 return oparg-1;
985 case UNPACK_EX:
986 return (oparg&0xFF) + (oparg>>8);
987 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200988 /* -1 at end of iterator, 1 if continue iterating. */
989 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 case STORE_ATTR:
992 return -2;
993 case DELETE_ATTR:
994 return -1;
995 case STORE_GLOBAL:
996 return -1;
997 case DELETE_GLOBAL:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_CONST:
1000 return 1;
1001 case LOAD_NAME:
1002 return 1;
1003 case BUILD_TUPLE:
1004 case BUILD_LIST:
1005 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001006 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001008 case BUILD_LIST_UNPACK:
1009 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001010 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_SET_UNPACK:
1012 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001014 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001016 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001017 case BUILD_CONST_KEY_MAP:
1018 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case LOAD_ATTR:
1020 return 0;
1021 case COMPARE_OP:
1022 return -1;
1023 case IMPORT_NAME:
1024 return -1;
1025 case IMPORT_FROM:
1026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001028 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_ABSOLUTE:
1031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 case JUMP_IF_TRUE_OR_POP:
1034 case JUMP_IF_FALSE_OR_POP:
1035 return jump ? 0 : -1;
1036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case POP_JUMP_IF_FALSE:
1038 case POP_JUMP_IF_TRUE:
1039 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_GLOBAL:
1042 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001044 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001046 /* 0 in the normal flow.
1047 * Restore the stack position and push 6 values before jumping to
1048 * the handler if an exception be raised. */
1049 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001050 case BEGIN_FINALLY:
1051 /* Actually pushes 1 value, but count 6 for balancing with
1052 * END_FINALLY and POP_FINALLY.
1053 * This is the main reason of using this opcode instead of
1054 * "LOAD_CONST None". */
1055 return 6;
1056 case CALL_FINALLY:
1057 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case LOAD_FAST:
1060 return 1;
1061 case STORE_FAST:
1062 return -1;
1063 case DELETE_FAST:
1064 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 case RAISE_VARARGS:
1067 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001068
1069 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001071 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001072 case CALL_METHOD:
1073 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001075 return -oparg-1;
1076 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001077 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001078 case MAKE_FUNCTION:
1079 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1080 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 case BUILD_SLICE:
1082 if (oparg == 3)
1083 return -2;
1084 else
1085 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001087 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 case LOAD_CLOSURE:
1089 return 1;
1090 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001091 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return 1;
1093 case STORE_DEREF:
1094 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001095 case DELETE_DEREF:
1096 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001097
1098 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001099 case GET_AWAITABLE:
1100 return 0;
1101 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001102 /* 0 in the normal flow.
1103 * Restore the stack position to the position before the result
1104 * of __aenter__ and push 6 values before jumping to the handler
1105 * if an exception be raised. */
1106 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001107 case BEFORE_ASYNC_WITH:
1108 return 1;
1109 case GET_AITER:
1110 return 0;
1111 case GET_ANEXT:
1112 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001113 case GET_YIELD_FROM_ITER:
1114 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001115 case END_ASYNC_FOR:
1116 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001117 case FORMAT_VALUE:
1118 /* If there's a fmt_spec on the stack, we go from 2->1,
1119 else 1->1. */
1120 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001121 case LOAD_METHOD:
1122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001124 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
Larry Hastings3a907972013-11-23 14:49:22 -08001126 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127}
1128
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001129int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001130PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1131{
1132 return stack_effect(opcode, oparg, jump);
1133}
1134
1135int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001136PyCompile_OpcodeStackEffect(int opcode, int oparg)
1137{
1138 return stack_effect(opcode, oparg, -1);
1139}
1140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141/* Add an opcode with no argument.
1142 Returns 0 on failure, 1 on success.
1143*/
1144
1145static int
1146compiler_addop(struct compiler *c, int opcode)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 basicblock *b;
1149 struct instr *i;
1150 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001151 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 off = compiler_next_instr(c, c->u->u_curblock);
1153 if (off < 0)
1154 return 0;
1155 b = c->u->u_curblock;
1156 i = &b->b_instr[off];
1157 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001158 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (opcode == RETURN_VALUE)
1160 b->b_return = 1;
1161 compiler_set_lineno(c, off);
1162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163}
1164
Victor Stinnerf8e32212013-11-19 23:56:34 +01001165static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1167{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001168 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001173 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001175 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001176 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return -1;
1180 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_DECREF(v);
1183 return -1;
1184 }
1185 Py_DECREF(v);
1186 }
1187 else
1188 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001189 return arg;
1190}
1191
INADA Naokic2e16072018-11-26 21:23:22 +09001192// Merge const *o* recursively and return constant key object.
1193static PyObject*
1194merge_consts_recursive(struct compiler *c, PyObject *o)
1195{
1196 // None and Ellipsis are singleton, and key is the singleton.
1197 // No need to merge object and key.
1198 if (o == Py_None || o == Py_Ellipsis) {
1199 Py_INCREF(o);
1200 return o;
1201 }
1202
1203 PyObject *key = _PyCode_ConstantKey(o);
1204 if (key == NULL) {
1205 return NULL;
1206 }
1207
1208 // t is borrowed reference
1209 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1210 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001211 // o is registered in c_const_cache. Just use it.
INADA Naokic2e16072018-11-26 21:23:22 +09001212 Py_INCREF(t);
1213 Py_DECREF(key);
1214 return t;
1215 }
1216
INADA Naokif7e4d362018-11-29 00:58:46 +09001217 // We registered o in c_const_cache.
1218 // When o is a tuple or frozenset, we want to merge it's
1219 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001220 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 Py_ssize_t len = PyTuple_GET_SIZE(o);
1222 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001223 PyObject *item = PyTuple_GET_ITEM(o, i);
1224 PyObject *u = merge_consts_recursive(c, item);
1225 if (u == NULL) {
1226 Py_DECREF(key);
1227 return NULL;
1228 }
1229
1230 // See _PyCode_ConstantKey()
1231 PyObject *v; // borrowed
1232 if (PyTuple_CheckExact(u)) {
1233 v = PyTuple_GET_ITEM(u, 1);
1234 }
1235 else {
1236 v = u;
1237 }
1238 if (v != item) {
1239 Py_INCREF(v);
1240 PyTuple_SET_ITEM(o, i, v);
1241 Py_DECREF(item);
1242 }
1243
1244 Py_DECREF(u);
1245 }
1246 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001247 else if (PyFrozenSet_CheckExact(o)) {
1248 // *key* is tuple. And it's first item is frozenset of
1249 // constant keys.
1250 // See _PyCode_ConstantKey() for detail.
1251 assert(PyTuple_CheckExact(key));
1252 assert(PyTuple_GET_SIZE(key) == 2);
1253
1254 Py_ssize_t len = PySet_GET_SIZE(o);
1255 if (len == 0) { // empty frozenset should not be re-created.
1256 return key;
1257 }
1258 PyObject *tuple = PyTuple_New(len);
1259 if (tuple == NULL) {
1260 Py_DECREF(key);
1261 return NULL;
1262 }
1263 Py_ssize_t i = 0, pos = 0;
1264 PyObject *item;
1265 Py_hash_t hash;
1266 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1267 PyObject *k = merge_consts_recursive(c, item);
1268 if (k == NULL) {
1269 Py_DECREF(tuple);
1270 Py_DECREF(key);
1271 return NULL;
1272 }
1273 PyObject *u;
1274 if (PyTuple_CheckExact(k)) {
1275 u = PyTuple_GET_ITEM(k, 1);
1276 Py_INCREF(u);
1277 Py_DECREF(k);
1278 }
1279 else {
1280 u = k;
1281 }
1282 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1283 i++;
1284 }
1285
1286 // Instead of rewriting o, we create new frozenset and embed in the
1287 // key tuple. Caller should get merged frozenset from the key tuple.
1288 PyObject *new = PyFrozenSet_New(tuple);
1289 Py_DECREF(tuple);
1290 if (new == NULL) {
1291 Py_DECREF(key);
1292 return NULL;
1293 }
1294 assert(PyTuple_GET_ITEM(key, 1) == o);
1295 Py_DECREF(o);
1296 PyTuple_SET_ITEM(key, 1, new);
1297 }
INADA Naokic2e16072018-11-26 21:23:22 +09001298
1299 return key;
1300}
1301
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001302static Py_ssize_t
1303compiler_add_const(struct compiler *c, PyObject *o)
1304{
INADA Naokic2e16072018-11-26 21:23:22 +09001305 PyObject *key = merge_consts_recursive(c, o);
1306 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001308 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001309
INADA Naokic2e16072018-11-26 21:23:22 +09001310 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1311 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
1315static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316compiler_addop_load_const(struct compiler *c, PyObject *o)
1317{
1318 Py_ssize_t arg = compiler_add_const(c, o);
1319 if (arg < 0)
1320 return 0;
1321 return compiler_addop_i(c, LOAD_CONST, arg);
1322}
1323
1324static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001328 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 return compiler_addop_i(c, opcode, arg);
1332}
1333
1334static int
1335compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001338 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1340 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 arg = compiler_add_o(c, dict, mangled);
1343 Py_DECREF(mangled);
1344 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 return compiler_addop_i(c, opcode, arg);
1347}
1348
1349/* Add an opcode with an integer argument.
1350 Returns 0 on failure, 1 on success.
1351*/
1352
1353static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001354compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 struct instr *i;
1357 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358
Victor Stinner2ad474b2016-03-01 23:34:47 +01001359 /* oparg value is unsigned, but a signed C int is usually used to store
1360 it in the C code (like Python/ceval.c).
1361
1362 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1363
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001364 The argument of a concrete bytecode instruction is limited to 8-bit.
1365 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1366 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001367 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 off = compiler_next_instr(c, c->u->u_curblock);
1370 if (off < 0)
1371 return 0;
1372 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001373 i->i_opcode = opcode;
1374 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 compiler_set_lineno(c, off);
1376 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377}
1378
1379static int
1380compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 struct instr *i;
1383 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001385 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 assert(b != NULL);
1387 off = compiler_next_instr(c, c->u->u_curblock);
1388 if (off < 0)
1389 return 0;
1390 i = &c->u->u_curblock->b_instr[off];
1391 i->i_opcode = opcode;
1392 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (absolute)
1394 i->i_jabs = 1;
1395 else
1396 i->i_jrel = 1;
1397 compiler_set_lineno(c, off);
1398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399}
1400
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001401/* NEXT_BLOCK() creates an implicit jump from the current block
1402 to the new block.
1403
1404 The returns inside this macro make it impossible to decref objects
1405 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (compiler_next_block((C)) == NULL) \
1409 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
1412#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!compiler_addop((C), (OP))) \
1414 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415}
1416
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001417#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!compiler_addop((C), (OP))) { \
1419 compiler_exit_scope(c); \
1420 return 0; \
1421 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001422}
1423
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001424#define ADDOP_LOAD_CONST(C, O) { \
1425 if (!compiler_addop_load_const((C), (O))) \
1426 return 0; \
1427}
1428
1429/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1430#define ADDOP_LOAD_CONST_NEW(C, O) { \
1431 PyObject *__new_const = (O); \
1432 if (__new_const == NULL) { \
1433 return 0; \
1434 } \
1435 if (!compiler_addop_load_const((C), __new_const)) { \
1436 Py_DECREF(__new_const); \
1437 return 0; \
1438 } \
1439 Py_DECREF(__new_const); \
1440}
1441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1444 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001447/* Same as ADDOP_O, but steals a reference. */
1448#define ADDOP_N(C, OP, O, TYPE) { \
1449 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1450 Py_DECREF((O)); \
1451 return 0; \
1452 } \
1453 Py_DECREF((O)); \
1454}
1455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1458 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459}
1460
1461#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_addop_i((C), (OP), (O))) \
1463 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_j((C), (OP), (O), 1)) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_j((C), (OP), (O), 0)) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
1476/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1477 the ASDL name to synthesize the name of the C type and the visit function.
1478*/
1479
1480#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_visit_ ## TYPE((C), (V))) \
1482 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483}
1484
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001485#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_visit_ ## TYPE((C), (V))) { \
1487 compiler_exit_scope(c); \
1488 return 0; \
1489 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001490}
1491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!compiler_visit_slice((C), (V), (CTX))) \
1494 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495}
1496
1497#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 int _i; \
1499 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1500 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1501 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1502 if (!compiler_visit_ ## TYPE((C), elt)) \
1503 return 0; \
1504 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001507#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 int _i; \
1509 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1510 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1511 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1512 if (!compiler_visit_ ## TYPE((C), elt)) { \
1513 compiler_exit_scope(c); \
1514 return 0; \
1515 } \
1516 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001517}
1518
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001519/* Search if variable annotations are present statically in a block. */
1520
1521static int
1522find_ann(asdl_seq *stmts)
1523{
1524 int i, j, res = 0;
1525 stmt_ty st;
1526
1527 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1528 st = (stmt_ty)asdl_seq_GET(stmts, i);
1529 switch (st->kind) {
1530 case AnnAssign_kind:
1531 return 1;
1532 case For_kind:
1533 res = find_ann(st->v.For.body) ||
1534 find_ann(st->v.For.orelse);
1535 break;
1536 case AsyncFor_kind:
1537 res = find_ann(st->v.AsyncFor.body) ||
1538 find_ann(st->v.AsyncFor.orelse);
1539 break;
1540 case While_kind:
1541 res = find_ann(st->v.While.body) ||
1542 find_ann(st->v.While.orelse);
1543 break;
1544 case If_kind:
1545 res = find_ann(st->v.If.body) ||
1546 find_ann(st->v.If.orelse);
1547 break;
1548 case With_kind:
1549 res = find_ann(st->v.With.body);
1550 break;
1551 case AsyncWith_kind:
1552 res = find_ann(st->v.AsyncWith.body);
1553 break;
1554 case Try_kind:
1555 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1556 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1557 st->v.Try.handlers, j);
1558 if (find_ann(handler->v.ExceptHandler.body)) {
1559 return 1;
1560 }
1561 }
1562 res = find_ann(st->v.Try.body) ||
1563 find_ann(st->v.Try.finalbody) ||
1564 find_ann(st->v.Try.orelse);
1565 break;
1566 default:
1567 res = 0;
1568 }
1569 if (res) {
1570 break;
1571 }
1572 }
1573 return res;
1574}
1575
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001576/*
1577 * Frame block handling functions
1578 */
1579
1580static int
1581compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1582 basicblock *exit)
1583{
1584 struct fblockinfo *f;
1585 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1586 PyErr_SetString(PyExc_SyntaxError,
1587 "too many statically nested blocks");
1588 return 0;
1589 }
1590 f = &c->u->u_fblock[c->u->u_nfblocks++];
1591 f->fb_type = t;
1592 f->fb_block = b;
1593 f->fb_exit = exit;
1594 return 1;
1595}
1596
1597static void
1598compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1599{
1600 struct compiler_unit *u = c->u;
1601 assert(u->u_nfblocks > 0);
1602 u->u_nfblocks--;
1603 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1604 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1605}
1606
1607/* Unwind a frame block. If preserve_tos is true, the TOS before
1608 * popping the blocks will be restored afterwards.
1609 */
1610static int
1611compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1612 int preserve_tos)
1613{
1614 switch (info->fb_type) {
1615 case WHILE_LOOP:
1616 return 1;
1617
1618 case FINALLY_END:
1619 ADDOP_I(c, POP_FINALLY, preserve_tos);
1620 return 1;
1621
1622 case FOR_LOOP:
1623 /* Pop the iterator */
1624 if (preserve_tos) {
1625 ADDOP(c, ROT_TWO);
1626 }
1627 ADDOP(c, POP_TOP);
1628 return 1;
1629
1630 case EXCEPT:
1631 ADDOP(c, POP_BLOCK);
1632 return 1;
1633
1634 case FINALLY_TRY:
1635 ADDOP(c, POP_BLOCK);
1636 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1637 return 1;
1638
1639 case WITH:
1640 case ASYNC_WITH:
1641 ADDOP(c, POP_BLOCK);
1642 if (preserve_tos) {
1643 ADDOP(c, ROT_TWO);
1644 }
1645 ADDOP(c, BEGIN_FINALLY);
1646 ADDOP(c, WITH_CLEANUP_START);
1647 if (info->fb_type == ASYNC_WITH) {
1648 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001649 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001650 ADDOP(c, YIELD_FROM);
1651 }
1652 ADDOP(c, WITH_CLEANUP_FINISH);
1653 ADDOP_I(c, POP_FINALLY, 0);
1654 return 1;
1655
1656 case HANDLER_CLEANUP:
1657 if (preserve_tos) {
1658 ADDOP(c, ROT_FOUR);
1659 }
1660 if (info->fb_exit) {
1661 ADDOP(c, POP_BLOCK);
1662 ADDOP(c, POP_EXCEPT);
1663 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1664 }
1665 else {
1666 ADDOP(c, POP_EXCEPT);
1667 }
1668 return 1;
1669 }
1670 Py_UNREACHABLE();
1671}
1672
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001673/* Compile a sequence of statements, checking for a docstring
1674 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
1676static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001677compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001679 int i = 0;
1680 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001681 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001682
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001683 /* Set current line number to the line number of first statement.
1684 This way line number for SETUP_ANNOTATIONS will always
1685 coincide with the line number of first "real" statement in module.
1686 If body is empy, then lineno will be set later in assemble. */
1687 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1688 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001689 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001690 c->u->u_lineno = st->lineno;
1691 }
1692 /* Every annotated class and module should have __annotations__. */
1693 if (find_ann(stmts)) {
1694 ADDOP(c, SETUP_ANNOTATIONS);
1695 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001696 if (!asdl_seq_LEN(stmts))
1697 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001698 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001699 if (c->c_optimize < 2) {
1700 docstring = _PyAST_GetDocString(stmts);
1701 if (docstring) {
1702 i = 1;
1703 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1704 assert(st->kind == Expr_kind);
1705 VISIT(c, expr, st->v.Expr.value);
1706 if (!compiler_nameop(c, __doc__, Store))
1707 return 0;
1708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001710 for (; i < asdl_seq_LEN(stmts); i++)
1711 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713}
1714
1715static PyCodeObject *
1716compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyCodeObject *co;
1719 int addNone = 1;
1720 static PyObject *module;
1721 if (!module) {
1722 module = PyUnicode_InternFromString("<module>");
1723 if (!module)
1724 return NULL;
1725 }
1726 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001727 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return NULL;
1729 switch (mod->kind) {
1730 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001731 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 compiler_exit_scope(c);
1733 return 0;
1734 }
1735 break;
1736 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001737 if (find_ann(mod->v.Interactive.body)) {
1738 ADDOP(c, SETUP_ANNOTATIONS);
1739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 c->c_interactive = 1;
1741 VISIT_SEQ_IN_SCOPE(c, stmt,
1742 mod->v.Interactive.body);
1743 break;
1744 case Expression_kind:
1745 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1746 addNone = 0;
1747 break;
1748 case Suite_kind:
1749 PyErr_SetString(PyExc_SystemError,
1750 "suite should not be possible");
1751 return 0;
1752 default:
1753 PyErr_Format(PyExc_SystemError,
1754 "module kind %d should not be possible",
1755 mod->kind);
1756 return 0;
1757 }
1758 co = assemble(c, addNone);
1759 compiler_exit_scope(c);
1760 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001761}
1762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763/* The test for LOCAL must come before the test for FREE in order to
1764 handle classes where name is both local and free. The local var is
1765 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001766*/
1767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768static int
1769get_ref_type(struct compiler *c, PyObject *name)
1770{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001771 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001772 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001773 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001774 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001775 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (scope == 0) {
1777 char buf[350];
1778 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001779 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001781 PyUnicode_AsUTF8(name),
1782 PyUnicode_AsUTF8(c->u->u_name),
1783 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1784 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1785 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 );
1788 Py_FatalError(buf);
1789 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792}
1793
1794static int
1795compiler_lookup_arg(PyObject *dict, PyObject *name)
1796{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001797 PyObject *v;
1798 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001800 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001801 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802}
1803
1804static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001805compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001807 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001808 if (qualname == NULL)
1809 qualname = co->co_name;
1810
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 if (free) {
1812 for (i = 0; i < free; ++i) {
1813 /* Bypass com_addop_varname because it will generate
1814 LOAD_DEREF but LOAD_CLOSURE is needed.
1815 */
1816 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1817 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001819 /* Special case: If a class contains a method with a
1820 free variable that has the same name as a method,
1821 the name will be considered free *and* local in the
1822 class. It should be handled by the closure, as
1823 well as by the normal name loookup logic.
1824 */
1825 reftype = get_ref_type(c, name);
1826 if (reftype == CELL)
1827 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1828 else /* (reftype == FREE) */
1829 arg = compiler_lookup_arg(c->u->u_freevars, name);
1830 if (arg == -1) {
1831 fprintf(stderr,
1832 "lookup %s in %s %d %d\n"
1833 "freevars of %s: %s\n",
1834 PyUnicode_AsUTF8(PyObject_Repr(name)),
1835 PyUnicode_AsUTF8(c->u->u_name),
1836 reftype, arg,
1837 PyUnicode_AsUTF8(co->co_name),
1838 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1839 Py_FatalError("compiler_make_closure()");
1840 }
1841 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001843 flags |= 0x08;
1844 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001846 ADDOP_LOAD_CONST(c, (PyObject*)co);
1847 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
1852static int
1853compiler_decorators(struct compiler *c, asdl_seq* decos)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (!decos)
1858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1861 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1862 }
1863 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864}
1865
1866static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001867compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001869{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001870 /* Push a dict of keyword-only default values.
1871
1872 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1873 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001874 int i;
1875 PyObject *keys = NULL;
1876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1878 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1879 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1880 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001881 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001882 if (!mangled) {
1883 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 if (keys == NULL) {
1886 keys = PyList_New(1);
1887 if (keys == NULL) {
1888 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001889 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001890 }
1891 PyList_SET_ITEM(keys, 0, mangled);
1892 }
1893 else {
1894 int res = PyList_Append(keys, mangled);
1895 Py_DECREF(mangled);
1896 if (res == -1) {
1897 goto error;
1898 }
1899 }
1900 if (!compiler_visit_expr(c, default_)) {
1901 goto error;
1902 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 }
1904 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905 if (keys != NULL) {
1906 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1907 PyObject *keys_tuple = PyList_AsTuple(keys);
1908 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001909 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001911 assert(default_count > 0);
1912 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 }
1914 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001915 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 }
1917
1918error:
1919 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001920 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001921}
1922
1923static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001924compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1925{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001926 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001927 return 1;
1928}
1929
1930static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001931compiler_visit_argannotation(struct compiler *c, identifier id,
1932 expr_ty annotation, PyObject *names)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001935 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001936 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1937 VISIT(c, annexpr, annotation)
1938 }
1939 else {
1940 VISIT(c, expr, annotation);
1941 }
Victor Stinner065efc32014-02-18 22:07:56 +01001942 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001943 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001944 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001945 if (PyList_Append(names, mangled) < 0) {
1946 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001947 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001948 }
1949 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001951 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001952}
1953
1954static int
1955compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1956 PyObject *names)
1957{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001958 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 for (i = 0; i < asdl_seq_LEN(args); i++) {
1960 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001961 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 c,
1963 arg->arg,
1964 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001965 names))
1966 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001968 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001969}
1970
1971static int
1972compiler_visit_annotations(struct compiler *c, arguments_ty args,
1973 expr_ty returns)
1974{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001975 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001976 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001977
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001978 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 */
1980 static identifier return_str;
1981 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001982 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 names = PyList_New(0);
1984 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001985 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001986
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001987 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001989 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001990 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001991 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001993 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001995 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001996 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001997 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (!return_str) {
2001 return_str = PyUnicode_InternFromString("return");
2002 if (!return_str)
2003 goto error;
2004 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002005 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 goto error;
2007 }
2008
2009 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 PyObject *keytuple = PyList_AsTuple(names);
2012 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002013 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002015 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 else {
2018 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002019 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002021
2022error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002024 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002025}
2026
2027static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028compiler_visit_defaults(struct compiler *c, arguments_ty args)
2029{
2030 VISIT_SEQ(c, expr, args->defaults);
2031 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033}
2034
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002035static Py_ssize_t
2036compiler_default_arguments(struct compiler *c, arguments_ty args)
2037{
2038 Py_ssize_t funcflags = 0;
2039 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 if (!compiler_visit_defaults(c, args))
2041 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042 funcflags |= 0x01;
2043 }
2044 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002045 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002046 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002047 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002048 return -1;
2049 }
2050 else if (res > 0) {
2051 funcflags |= 0x02;
2052 }
2053 }
2054 return funcflags;
2055}
2056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057static int
Yury Selivanov75445082015-05-11 22:57:16 -04002058compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002061 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002062 arguments_ty args;
2063 expr_ty returns;
2064 identifier name;
2065 asdl_seq* decos;
2066 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002067 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002068 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002069 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002070 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071
Yury Selivanov75445082015-05-11 22:57:16 -04002072 if (is_async) {
2073 assert(s->kind == AsyncFunctionDef_kind);
2074
2075 args = s->v.AsyncFunctionDef.args;
2076 returns = s->v.AsyncFunctionDef.returns;
2077 decos = s->v.AsyncFunctionDef.decorator_list;
2078 name = s->v.AsyncFunctionDef.name;
2079 body = s->v.AsyncFunctionDef.body;
2080
2081 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2082 } else {
2083 assert(s->kind == FunctionDef_kind);
2084
2085 args = s->v.FunctionDef.args;
2086 returns = s->v.FunctionDef.returns;
2087 decos = s->v.FunctionDef.decorator_list;
2088 name = s->v.FunctionDef.name;
2089 body = s->v.FunctionDef.body;
2090
2091 scope_type = COMPILER_SCOPE_FUNCTION;
2092 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (!compiler_decorators(c, decos))
2095 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002096
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002097 firstlineno = s->lineno;
2098 if (asdl_seq_LEN(decos)) {
2099 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2100 }
2101
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002102 funcflags = compiler_default_arguments(c, args);
2103 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105 }
2106
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002107 annotations = compiler_visit_annotations(c, args, returns);
2108 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 return 0;
2110 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002111 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 funcflags |= 0x04;
2113 }
2114
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002115 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 return 0;
2117 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118
INADA Naokicb41b272017-02-23 00:31:59 +09002119 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002120 if (c->c_optimize < 2) {
2121 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002122 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002123 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 compiler_exit_scope(c);
2125 return 0;
2126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 c->u->u_argcount = asdl_seq_LEN(args->args);
2129 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002130 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002132 qualname = c->u->u_qualname;
2133 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002135 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002136 Py_XDECREF(qualname);
2137 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002139 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002142 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* decorators */
2146 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2147 ADDOP_I(c, CALL_FUNCTION, 1);
2148 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149
Yury Selivanov75445082015-05-11 22:57:16 -04002150 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151}
2152
2153static int
2154compiler_class(struct compiler *c, stmt_ty s)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyCodeObject *co;
2157 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002158 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (!compiler_decorators(c, decos))
2162 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002163
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002164 firstlineno = s->lineno;
2165 if (asdl_seq_LEN(decos)) {
2166 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2167 }
2168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* ultimately generate code for:
2170 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2171 where:
2172 <func> is a function/closure created from the class body;
2173 it has a single argument (__locals__) where the dict
2174 (or MutableSequence) representing the locals is passed
2175 <name> is the class name
2176 <bases> is the positional arguments and *varargs argument
2177 <keywords> is the keyword arguments and **kwds argument
2178 This borrows from compiler_call.
2179 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002182 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002183 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return 0;
2185 /* this block represents what we do in the new scope */
2186 {
2187 /* use the class name for name mangling */
2188 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002189 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* load (global) __name__ ... */
2191 str = PyUnicode_InternFromString("__name__");
2192 if (!str || !compiler_nameop(c, str, Load)) {
2193 Py_XDECREF(str);
2194 compiler_exit_scope(c);
2195 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_DECREF(str);
2198 /* ... and store it as __module__ */
2199 str = PyUnicode_InternFromString("__module__");
2200 if (!str || !compiler_nameop(c, str, Store)) {
2201 Py_XDECREF(str);
2202 compiler_exit_scope(c);
2203 return 0;
2204 }
2205 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002206 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002207 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002208 str = PyUnicode_InternFromString("__qualname__");
2209 if (!str || !compiler_nameop(c, str, Store)) {
2210 Py_XDECREF(str);
2211 compiler_exit_scope(c);
2212 return 0;
2213 }
2214 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002216 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 compiler_exit_scope(c);
2218 return 0;
2219 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002220 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002221 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002222 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002223 str = PyUnicode_InternFromString("__class__");
2224 if (str == NULL) {
2225 compiler_exit_scope(c);
2226 return 0;
2227 }
2228 i = compiler_lookup_arg(c->u->u_cellvars, str);
2229 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002230 if (i < 0) {
2231 compiler_exit_scope(c);
2232 return 0;
2233 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002234 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002237 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002238 str = PyUnicode_InternFromString("__classcell__");
2239 if (!str || !compiler_nameop(c, str, Store)) {
2240 Py_XDECREF(str);
2241 compiler_exit_scope(c);
2242 return 0;
2243 }
2244 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002246 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002247 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002248 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002249 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002250 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002251 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* create the code object */
2253 co = assemble(c, 1);
2254 }
2255 /* leave the new scope */
2256 compiler_exit_scope(c);
2257 if (co == NULL)
2258 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* 2. load the 'build_class' function */
2261 ADDOP(c, LOAD_BUILD_CLASS);
2262
2263 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002264 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 Py_DECREF(co);
2266
2267 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002268 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269
2270 /* 5. generate the rest of the code for the call */
2271 if (!compiler_call_helper(c, 2,
2272 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002273 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 0;
2275
2276 /* 6. apply decorators */
2277 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2278 ADDOP_I(c, CALL_FUNCTION, 1);
2279 }
2280
2281 /* 7. store into <name> */
2282 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2283 return 0;
2284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002287/* Return 0 if the expression is a constant value except named singletons.
2288 Return 1 otherwise. */
2289static int
2290check_is_arg(expr_ty e)
2291{
2292 if (e->kind != Constant_kind) {
2293 return 1;
2294 }
2295 PyObject *value = e->v.Constant.value;
2296 return (value == Py_None
2297 || value == Py_False
2298 || value == Py_True
2299 || value == Py_Ellipsis);
2300}
2301
2302/* Check operands of identity chacks ("is" and "is not").
2303 Emit a warning if any operand is a constant except named singletons.
2304 Return 0 on error.
2305 */
2306static int
2307check_compare(struct compiler *c, expr_ty e)
2308{
2309 Py_ssize_t i, n;
2310 int left = check_is_arg(e->v.Compare.left);
2311 n = asdl_seq_LEN(e->v.Compare.ops);
2312 for (i = 0; i < n; i++) {
2313 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2314 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2315 if (op == Is || op == IsNot) {
2316 if (!right || !left) {
2317 const char *msg = (op == Is)
2318 ? "\"is\" with a literal. Did you mean \"==\"?"
2319 : "\"is not\" with a literal. Did you mean \"!=\"?";
2320 return compiler_warn(c, msg);
2321 }
2322 }
2323 left = right;
2324 }
2325 return 1;
2326}
2327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002329cmpop(cmpop_ty op)
2330{
2331 switch (op) {
2332 case Eq:
2333 return PyCmp_EQ;
2334 case NotEq:
2335 return PyCmp_NE;
2336 case Lt:
2337 return PyCmp_LT;
2338 case LtE:
2339 return PyCmp_LE;
2340 case Gt:
2341 return PyCmp_GT;
2342 case GtE:
2343 return PyCmp_GE;
2344 case Is:
2345 return PyCmp_IS;
2346 case IsNot:
2347 return PyCmp_IS_NOT;
2348 case In:
2349 return PyCmp_IN;
2350 case NotIn:
2351 return PyCmp_NOT_IN;
2352 default:
2353 return PyCmp_BAD;
2354 }
2355}
2356
2357static int
2358compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2359{
2360 switch (e->kind) {
2361 case UnaryOp_kind:
2362 if (e->v.UnaryOp.op == Not)
2363 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2364 /* fallback to general implementation */
2365 break;
2366 case BoolOp_kind: {
2367 asdl_seq *s = e->v.BoolOp.values;
2368 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2369 assert(n >= 0);
2370 int cond2 = e->v.BoolOp.op == Or;
2371 basicblock *next2 = next;
2372 if (!cond2 != !cond) {
2373 next2 = compiler_new_block(c);
2374 if (next2 == NULL)
2375 return 0;
2376 }
2377 for (i = 0; i < n; ++i) {
2378 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2379 return 0;
2380 }
2381 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2382 return 0;
2383 if (next2 != next)
2384 compiler_use_next_block(c, next2);
2385 return 1;
2386 }
2387 case IfExp_kind: {
2388 basicblock *end, *next2;
2389 end = compiler_new_block(c);
2390 if (end == NULL)
2391 return 0;
2392 next2 = compiler_new_block(c);
2393 if (next2 == NULL)
2394 return 0;
2395 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2396 return 0;
2397 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2398 return 0;
2399 ADDOP_JREL(c, JUMP_FORWARD, end);
2400 compiler_use_next_block(c, next2);
2401 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2402 return 0;
2403 compiler_use_next_block(c, end);
2404 return 1;
2405 }
2406 case Compare_kind: {
2407 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2408 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002409 if (!check_compare(c, e)) {
2410 return 0;
2411 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002412 basicblock *cleanup = compiler_new_block(c);
2413 if (cleanup == NULL)
2414 return 0;
2415 VISIT(c, expr, e->v.Compare.left);
2416 for (i = 0; i < n; i++) {
2417 VISIT(c, expr,
2418 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2419 ADDOP(c, DUP_TOP);
2420 ADDOP(c, ROT_THREE);
2421 ADDOP_I(c, COMPARE_OP,
2422 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2423 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2424 NEXT_BLOCK(c);
2425 }
2426 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2427 ADDOP_I(c, COMPARE_OP,
2428 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2429 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2430 basicblock *end = compiler_new_block(c);
2431 if (end == NULL)
2432 return 0;
2433 ADDOP_JREL(c, JUMP_FORWARD, end);
2434 compiler_use_next_block(c, cleanup);
2435 ADDOP(c, POP_TOP);
2436 if (!cond) {
2437 ADDOP_JREL(c, JUMP_FORWARD, next);
2438 }
2439 compiler_use_next_block(c, end);
2440 return 1;
2441 }
2442 /* fallback to general implementation */
2443 break;
2444 }
2445 default:
2446 /* fallback to general implementation */
2447 break;
2448 }
2449
2450 /* general implementation */
2451 VISIT(c, expr, e);
2452 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2453 return 1;
2454}
2455
2456static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002457compiler_ifexp(struct compiler *c, expr_ty e)
2458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 basicblock *end, *next;
2460
2461 assert(e->kind == IfExp_kind);
2462 end = compiler_new_block(c);
2463 if (end == NULL)
2464 return 0;
2465 next = compiler_new_block(c);
2466 if (next == NULL)
2467 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002468 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2469 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 VISIT(c, expr, e->v.IfExp.body);
2471 ADDOP_JREL(c, JUMP_FORWARD, end);
2472 compiler_use_next_block(c, next);
2473 VISIT(c, expr, e->v.IfExp.orelse);
2474 compiler_use_next_block(c, end);
2475 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002476}
2477
2478static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479compiler_lambda(struct compiler *c, expr_ty e)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002482 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002484 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 arguments_ty args = e->v.Lambda.args;
2486 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (!name) {
2489 name = PyUnicode_InternFromString("<lambda>");
2490 if (!name)
2491 return 0;
2492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002494 funcflags = compiler_default_arguments(c, args);
2495 if (funcflags == -1) {
2496 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002498
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002499 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002500 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* Make None the first constant, so the lambda can't have a
2504 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002505 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 c->u->u_argcount = asdl_seq_LEN(args->args);
2509 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2510 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2511 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002512 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 }
2514 else {
2515 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002516 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002518 qualname = c->u->u_qualname;
2519 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002521 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002524 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002525 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Py_DECREF(co);
2527
2528 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529}
2530
2531static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532compiler_if(struct compiler *c, stmt_ty s)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 basicblock *end, *next;
2535 int constant;
2536 assert(s->kind == If_kind);
2537 end = compiler_new_block(c);
2538 if (end == NULL)
2539 return 0;
2540
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002541 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* constant = 0: "if 0"
2543 * constant = 1: "if 1", "if 2", ...
2544 * constant = -1: rest */
2545 if (constant == 0) {
2546 if (s->v.If.orelse)
2547 VISIT_SEQ(c, stmt, s->v.If.orelse);
2548 } else if (constant == 1) {
2549 VISIT_SEQ(c, stmt, s->v.If.body);
2550 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002551 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 next = compiler_new_block(c);
2553 if (next == NULL)
2554 return 0;
2555 }
2556 else
2557 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002558 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2559 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002561 if (asdl_seq_LEN(s->v.If.orelse)) {
2562 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 compiler_use_next_block(c, next);
2564 VISIT_SEQ(c, stmt, s->v.If.orelse);
2565 }
2566 }
2567 compiler_use_next_block(c, end);
2568 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569}
2570
2571static int
2572compiler_for(struct compiler *c, stmt_ty s)
2573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 start = compiler_new_block(c);
2577 cleanup = compiler_new_block(c);
2578 end = compiler_new_block(c);
2579 if (start == NULL || end == NULL || cleanup == NULL)
2580 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002581
2582 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 VISIT(c, expr, s->v.For.iter);
2586 ADDOP(c, GET_ITER);
2587 compiler_use_next_block(c, start);
2588 ADDOP_JREL(c, FOR_ITER, cleanup);
2589 VISIT(c, expr, s->v.For.target);
2590 VISIT_SEQ(c, stmt, s->v.For.body);
2591 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2592 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002593
2594 compiler_pop_fblock(c, FOR_LOOP, start);
2595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 VISIT_SEQ(c, stmt, s->v.For.orelse);
2597 compiler_use_next_block(c, end);
2598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599}
2600
Yury Selivanov75445082015-05-11 22:57:16 -04002601
2602static int
2603compiler_async_for(struct compiler *c, stmt_ty s)
2604{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002605 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002606 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2607 return compiler_error(c, "'async for' outside async function");
2608 }
2609
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002610 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002611 except = compiler_new_block(c);
2612 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002613
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002614 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002615 return 0;
2616
2617 VISIT(c, expr, s->v.AsyncFor.iter);
2618 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002619
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002620 compiler_use_next_block(c, start);
2621 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2622 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002623
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002624 /* SETUP_FINALLY to guard the __anext__ call */
2625 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002626 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002627 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002628 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002629 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002630
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002631 /* Success block for __anext__ */
2632 VISIT(c, expr, s->v.AsyncFor.target);
2633 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2634 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2635
2636 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002637
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002638 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002639 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002640 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002641
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002642 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002643 VISIT_SEQ(c, stmt, s->v.For.orelse);
2644
2645 compiler_use_next_block(c, end);
2646
2647 return 1;
2648}
2649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650static int
2651compiler_while(struct compiler *c, stmt_ty s)
2652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002654 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (constant == 0) {
2657 if (s->v.While.orelse)
2658 VISIT_SEQ(c, stmt, s->v.While.orelse);
2659 return 1;
2660 }
2661 loop = compiler_new_block(c);
2662 end = compiler_new_block(c);
2663 if (constant == -1) {
2664 anchor = compiler_new_block(c);
2665 if (anchor == NULL)
2666 return 0;
2667 }
2668 if (loop == NULL || end == NULL)
2669 return 0;
2670 if (s->v.While.orelse) {
2671 orelse = compiler_new_block(c);
2672 if (orelse == NULL)
2673 return 0;
2674 }
2675 else
2676 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002679 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 return 0;
2681 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002682 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2683 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 }
2685 VISIT_SEQ(c, stmt, s->v.While.body);
2686 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* XXX should the two POP instructions be in a separate block
2689 if there is no else clause ?
2690 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002692 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002694 compiler_pop_fblock(c, WHILE_LOOP, loop);
2695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (orelse != NULL) /* what if orelse is just pass? */
2697 VISIT_SEQ(c, stmt, s->v.While.orelse);
2698 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701}
2702
2703static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002704compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002706 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002707 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002708 if (c->u->u_ste->ste_type != FunctionBlock)
2709 return compiler_error(c, "'return' outside function");
2710 if (s->v.Return.value != NULL &&
2711 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2712 {
2713 return compiler_error(
2714 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002716 if (preserve_tos) {
2717 VISIT(c, expr, s->v.Return.value);
2718 }
2719 for (int depth = c->u->u_nfblocks; depth--;) {
2720 struct fblockinfo *info = &c->u->u_fblock[depth];
2721
2722 if (!compiler_unwind_fblock(c, info, preserve_tos))
2723 return 0;
2724 }
2725 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002726 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002727 }
2728 else if (!preserve_tos) {
2729 VISIT(c, expr, s->v.Return.value);
2730 }
2731 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734}
2735
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002736static int
2737compiler_break(struct compiler *c)
2738{
2739 for (int depth = c->u->u_nfblocks; depth--;) {
2740 struct fblockinfo *info = &c->u->u_fblock[depth];
2741
2742 if (!compiler_unwind_fblock(c, info, 0))
2743 return 0;
2744 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2745 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2746 return 1;
2747 }
2748 }
2749 return compiler_error(c, "'break' outside loop");
2750}
2751
2752static int
2753compiler_continue(struct compiler *c)
2754{
2755 for (int depth = c->u->u_nfblocks; depth--;) {
2756 struct fblockinfo *info = &c->u->u_fblock[depth];
2757
2758 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2759 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2760 return 1;
2761 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002762 if (!compiler_unwind_fblock(c, info, 0))
2763 return 0;
2764 }
2765 return compiler_error(c, "'continue' not properly in loop");
2766}
2767
2768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770
2771 SETUP_FINALLY L
2772 <code for body>
2773 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 BEGIN_FINALLY
2775 L:
2776 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 END_FINALLY
2778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 The special instructions use the block stack. Each block
2780 stack entry contains the instruction that created it (here
2781 SETUP_FINALLY), the level of the value stack at the time the
2782 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 Pushes the current value stack level and the label
2786 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 Pops en entry from the block stack.
2789 BEGIN_FINALLY
2790 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2793 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002796 when a SETUP_FINALLY entry is found, the raised and the caught
2797 exceptions are pushed onto the value stack (and the exception
2798 condition is cleared), and the interpreter jumps to the label
2799 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800*/
2801
2802static int
2803compiler_try_finally(struct compiler *c, stmt_ty s)
2804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 body = compiler_new_block(c);
2808 end = compiler_new_block(c);
2809 if (body == NULL || end == NULL)
2810 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002812 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 ADDOP_JREL(c, SETUP_FINALLY, end);
2814 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002815 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002817 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2818 if (!compiler_try_except(c, s))
2819 return 0;
2820 }
2821 else {
2822 VISIT_SEQ(c, stmt, s->v.Try.body);
2823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002828 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002830 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002832 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 ADDOP(c, END_FINALLY);
2834 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836}
2837
2838/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002839 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 (The contents of the value stack is shown in [], with the top
2841 at the right; 'tb' is trace-back info, 'val' the exception's
2842 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843
2844 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 [] <code for S>
2847 [] POP_BLOCK
2848 [] JUMP_FORWARD L0
2849
2850 [tb, val, exc] L1: DUP )
2851 [tb, val, exc, exc] <evaluate E1> )
2852 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2853 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2854 [tb, val, exc] POP
2855 [tb, val] <assign to V1> (or POP if no V1)
2856 [tb] POP
2857 [] <code for S1>
2858 JUMP_FORWARD L0
2859
2860 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 .............................etc.......................
2862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2864
2865 [] L0: <next statement>
2866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 Of course, parts are not generated if Vi or Ei is not present.
2868*/
2869static int
2870compiler_try_except(struct compiler *c, stmt_ty s)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002873 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 body = compiler_new_block(c);
2876 except = compiler_new_block(c);
2877 orelse = compiler_new_block(c);
2878 end = compiler_new_block(c);
2879 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2880 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002885 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 ADDOP(c, POP_BLOCK);
2887 compiler_pop_fblock(c, EXCEPT, body);
2888 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002889 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 compiler_use_next_block(c, except);
2891 for (i = 0; i < n; i++) {
2892 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002893 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (!handler->v.ExceptHandler.type && i < n-1)
2895 return compiler_error(c, "default 'except:' must be last");
2896 c->u->u_lineno_set = 0;
2897 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002898 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 except = compiler_new_block(c);
2900 if (except == NULL)
2901 return 0;
2902 if (handler->v.ExceptHandler.type) {
2903 ADDOP(c, DUP_TOP);
2904 VISIT(c, expr, handler->v.ExceptHandler.type);
2905 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2906 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2907 }
2908 ADDOP(c, POP_TOP);
2909 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002910 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002911
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002912 cleanup_end = compiler_new_block(c);
2913 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002914 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002915 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002916 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002917
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002918 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2919 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002921 /*
2922 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002923 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002924 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002925 try:
2926 # body
2927 finally:
2928 name = None
2929 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002930 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002932 /* second try: */
2933 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2934 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002935 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002936 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002938 /* second # body */
2939 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2940 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 ADDOP(c, BEGIN_FINALLY);
2942 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002944 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002945 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002947 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002949 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002950 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002951 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002952 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002954 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002955 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002956 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 }
2958 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002959 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002961 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002962 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002963 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964
Guido van Rossumb940e112007-01-10 16:19:56 +00002965 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002966 ADDOP(c, POP_TOP);
2967 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002968 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002971 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002972 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 }
2974 ADDOP_JREL(c, JUMP_FORWARD, end);
2975 compiler_use_next_block(c, except);
2976 }
2977 ADDOP(c, END_FINALLY);
2978 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002979 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 compiler_use_next_block(c, end);
2981 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002985compiler_try(struct compiler *c, stmt_ty s) {
2986 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2987 return compiler_try_finally(c, s);
2988 else
2989 return compiler_try_except(c, s);
2990}
2991
2992
2993static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994compiler_import_as(struct compiler *c, identifier name, identifier asname)
2995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 /* The IMPORT_NAME opcode was already generated. This function
2997 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003000 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003002 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3003 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003004 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003005 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003008 while (1) {
3009 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003011 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003012 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003013 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003014 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003016 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003017 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003018 if (dot == -1) {
3019 break;
3020 }
3021 ADDOP(c, ROT_TWO);
3022 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003024 if (!compiler_nameop(c, asname, Store)) {
3025 return 0;
3026 }
3027 ADDOP(c, POP_TOP);
3028 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 }
3030 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031}
3032
3033static int
3034compiler_import(struct compiler *c, stmt_ty s)
3035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 /* The Import node stores a module name like a.b.c as a single
3037 string. This is convenient for all cases except
3038 import a.b.c as d
3039 where we need to parse that string to extract the individual
3040 module names.
3041 XXX Perhaps change the representation to make this case simpler?
3042 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003043 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 for (i = 0; i < n; i++) {
3046 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3047 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003049 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3050 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 if (alias->asname) {
3054 r = compiler_import_as(c, alias->name, alias->asname);
3055 if (!r)
3056 return r;
3057 }
3058 else {
3059 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003060 Py_ssize_t dot = PyUnicode_FindChar(
3061 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003062 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003063 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003064 if (tmp == NULL)
3065 return 0;
3066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003068 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 Py_DECREF(tmp);
3070 }
3071 if (!r)
3072 return r;
3073 }
3074 }
3075 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076}
3077
3078static int
3079compiler_from_import(struct compiler *c, stmt_ty s)
3080{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003081 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003082 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 if (!empty_string) {
3086 empty_string = PyUnicode_FromString("");
3087 if (!empty_string)
3088 return 0;
3089 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003091 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003092
3093 names = PyTuple_New(n);
3094 if (!names)
3095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 /* build up the names */
3098 for (i = 0; i < n; i++) {
3099 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3100 Py_INCREF(alias->name);
3101 PyTuple_SET_ITEM(names, i, alias->name);
3102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003105 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 Py_DECREF(names);
3107 return compiler_error(c, "from __future__ imports must occur "
3108 "at the beginning of the file");
3109 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003110 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 if (s->v.ImportFrom.module) {
3113 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3114 }
3115 else {
3116 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3117 }
3118 for (i = 0; i < n; i++) {
3119 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3120 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003122 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 assert(n == 1);
3124 ADDOP(c, IMPORT_STAR);
3125 return 1;
3126 }
3127
3128 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3129 store_name = alias->name;
3130 if (alias->asname)
3131 store_name = alias->asname;
3132
3133 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 return 0;
3135 }
3136 }
3137 /* remove imported module */
3138 ADDOP(c, POP_TOP);
3139 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140}
3141
3142static int
3143compiler_assert(struct compiler *c, stmt_ty s)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 static PyObject *assertion_error = NULL;
3146 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147
Georg Brandl8334fd92010-12-04 10:26:46 +00003148 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 return 1;
3150 if (assertion_error == NULL) {
3151 assertion_error = PyUnicode_InternFromString("AssertionError");
3152 if (assertion_error == NULL)
3153 return 0;
3154 }
3155 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003156 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3157 {
3158 if (!compiler_warn(c, "assertion is always true, "
3159 "perhaps remove parentheses?"))
3160 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003161 return 0;
3162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 end = compiler_new_block(c);
3165 if (end == NULL)
3166 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003167 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3168 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3170 if (s->v.Assert.msg) {
3171 VISIT(c, expr, s->v.Assert.msg);
3172 ADDOP_I(c, CALL_FUNCTION, 1);
3173 }
3174 ADDOP_I(c, RAISE_VARARGS, 1);
3175 compiler_use_next_block(c, end);
3176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177}
3178
3179static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003180compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3181{
3182 if (c->c_interactive && c->c_nestlevel <= 1) {
3183 VISIT(c, expr, value);
3184 ADDOP(c, PRINT_EXPR);
3185 return 1;
3186 }
3187
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003188 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003189 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003190 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003191 }
3192
3193 VISIT(c, expr, value);
3194 ADDOP(c, POP_TOP);
3195 return 1;
3196}
3197
3198static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199compiler_visit_stmt(struct compiler *c, stmt_ty s)
3200{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003201 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* Always assign a lineno to the next instruction for a stmt. */
3204 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003205 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 switch (s->kind) {
3209 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003210 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 case ClassDef_kind:
3212 return compiler_class(c, s);
3213 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003214 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 case Delete_kind:
3216 VISIT_SEQ(c, expr, s->v.Delete.targets)
3217 break;
3218 case Assign_kind:
3219 n = asdl_seq_LEN(s->v.Assign.targets);
3220 VISIT(c, expr, s->v.Assign.value);
3221 for (i = 0; i < n; i++) {
3222 if (i < n - 1)
3223 ADDOP(c, DUP_TOP);
3224 VISIT(c, expr,
3225 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3226 }
3227 break;
3228 case AugAssign_kind:
3229 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003230 case AnnAssign_kind:
3231 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 case For_kind:
3233 return compiler_for(c, s);
3234 case While_kind:
3235 return compiler_while(c, s);
3236 case If_kind:
3237 return compiler_if(c, s);
3238 case Raise_kind:
3239 n = 0;
3240 if (s->v.Raise.exc) {
3241 VISIT(c, expr, s->v.Raise.exc);
3242 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003243 if (s->v.Raise.cause) {
3244 VISIT(c, expr, s->v.Raise.cause);
3245 n++;
3246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003248 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003250 case Try_kind:
3251 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 case Assert_kind:
3253 return compiler_assert(c, s);
3254 case Import_kind:
3255 return compiler_import(c, s);
3256 case ImportFrom_kind:
3257 return compiler_from_import(c, s);
3258 case Global_kind:
3259 case Nonlocal_kind:
3260 break;
3261 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003262 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 case Pass_kind:
3264 break;
3265 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003266 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 case Continue_kind:
3268 return compiler_continue(c);
3269 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003270 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003271 case AsyncFunctionDef_kind:
3272 return compiler_function(c, s, 1);
3273 case AsyncWith_kind:
3274 return compiler_async_with(c, s, 0);
3275 case AsyncFor_kind:
3276 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 }
Yury Selivanov75445082015-05-11 22:57:16 -04003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280}
3281
3282static int
3283unaryop(unaryop_ty op)
3284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 switch (op) {
3286 case Invert:
3287 return UNARY_INVERT;
3288 case Not:
3289 return UNARY_NOT;
3290 case UAdd:
3291 return UNARY_POSITIVE;
3292 case USub:
3293 return UNARY_NEGATIVE;
3294 default:
3295 PyErr_Format(PyExc_SystemError,
3296 "unary op %d should not be possible", op);
3297 return 0;
3298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299}
3300
3301static int
3302binop(struct compiler *c, operator_ty op)
3303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 switch (op) {
3305 case Add:
3306 return BINARY_ADD;
3307 case Sub:
3308 return BINARY_SUBTRACT;
3309 case Mult:
3310 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003311 case MatMult:
3312 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 case Div:
3314 return BINARY_TRUE_DIVIDE;
3315 case Mod:
3316 return BINARY_MODULO;
3317 case Pow:
3318 return BINARY_POWER;
3319 case LShift:
3320 return BINARY_LSHIFT;
3321 case RShift:
3322 return BINARY_RSHIFT;
3323 case BitOr:
3324 return BINARY_OR;
3325 case BitXor:
3326 return BINARY_XOR;
3327 case BitAnd:
3328 return BINARY_AND;
3329 case FloorDiv:
3330 return BINARY_FLOOR_DIVIDE;
3331 default:
3332 PyErr_Format(PyExc_SystemError,
3333 "binary op %d should not be possible", op);
3334 return 0;
3335 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336}
3337
3338static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339inplace_binop(struct compiler *c, operator_ty op)
3340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 switch (op) {
3342 case Add:
3343 return INPLACE_ADD;
3344 case Sub:
3345 return INPLACE_SUBTRACT;
3346 case Mult:
3347 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003348 case MatMult:
3349 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 case Div:
3351 return INPLACE_TRUE_DIVIDE;
3352 case Mod:
3353 return INPLACE_MODULO;
3354 case Pow:
3355 return INPLACE_POWER;
3356 case LShift:
3357 return INPLACE_LSHIFT;
3358 case RShift:
3359 return INPLACE_RSHIFT;
3360 case BitOr:
3361 return INPLACE_OR;
3362 case BitXor:
3363 return INPLACE_XOR;
3364 case BitAnd:
3365 return INPLACE_AND;
3366 case FloorDiv:
3367 return INPLACE_FLOOR_DIVIDE;
3368 default:
3369 PyErr_Format(PyExc_SystemError,
3370 "inplace binary op %d should not be possible", op);
3371 return 0;
3372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373}
3374
3375static int
3376compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3377{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003378 int op, scope;
3379 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 PyObject *dict = c->u->u_names;
3383 PyObject *mangled;
3384 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003386 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3387 !_PyUnicode_EqualToASCIIString(name, "True") &&
3388 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003389
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003390 mangled = _Py_Mangle(c->u->u_private, name);
3391 if (!mangled)
3392 return 0;
3393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 op = 0;
3395 optype = OP_NAME;
3396 scope = PyST_GetScope(c->u->u_ste, mangled);
3397 switch (scope) {
3398 case FREE:
3399 dict = c->u->u_freevars;
3400 optype = OP_DEREF;
3401 break;
3402 case CELL:
3403 dict = c->u->u_cellvars;
3404 optype = OP_DEREF;
3405 break;
3406 case LOCAL:
3407 if (c->u->u_ste->ste_type == FunctionBlock)
3408 optype = OP_FAST;
3409 break;
3410 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003411 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 optype = OP_GLOBAL;
3413 break;
3414 case GLOBAL_EXPLICIT:
3415 optype = OP_GLOBAL;
3416 break;
3417 default:
3418 /* scope can be 0 */
3419 break;
3420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003423 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 switch (optype) {
3426 case OP_DEREF:
3427 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003428 case Load:
3429 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3430 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003431 case Store:
3432 case NamedStore:
3433 op = STORE_DEREF;
3434 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 case AugLoad:
3436 case AugStore:
3437 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003438 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 case Param:
3440 default:
3441 PyErr_SetString(PyExc_SystemError,
3442 "param invalid for deref variable");
3443 return 0;
3444 }
3445 break;
3446 case OP_FAST:
3447 switch (ctx) {
3448 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003449 case Store:
3450 case NamedStore:
3451 op = STORE_FAST;
3452 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 case Del: op = DELETE_FAST; break;
3454 case AugLoad:
3455 case AugStore:
3456 break;
3457 case Param:
3458 default:
3459 PyErr_SetString(PyExc_SystemError,
3460 "param invalid for local variable");
3461 return 0;
3462 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003463 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 return 1;
3465 case OP_GLOBAL:
3466 switch (ctx) {
3467 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003468 case Store:
3469 case NamedStore:
3470 op = STORE_GLOBAL;
3471 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 case Del: op = DELETE_GLOBAL; break;
3473 case AugLoad:
3474 case AugStore:
3475 break;
3476 case Param:
3477 default:
3478 PyErr_SetString(PyExc_SystemError,
3479 "param invalid for global variable");
3480 return 0;
3481 }
3482 break;
3483 case OP_NAME:
3484 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003485 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003486 case Store:
3487 case NamedStore:
3488 op = STORE_NAME;
3489 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 case Del: op = DELETE_NAME; break;
3491 case AugLoad:
3492 case AugStore:
3493 break;
3494 case Param:
3495 default:
3496 PyErr_SetString(PyExc_SystemError,
3497 "param invalid for name variable");
3498 return 0;
3499 }
3500 break;
3501 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 assert(op);
3504 arg = compiler_add_o(c, dict, mangled);
3505 Py_DECREF(mangled);
3506 if (arg < 0)
3507 return 0;
3508 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509}
3510
3511static int
3512compiler_boolop(struct compiler *c, expr_ty e)
3513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003515 int jumpi;
3516 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 assert(e->kind == BoolOp_kind);
3520 if (e->v.BoolOp.op == And)
3521 jumpi = JUMP_IF_FALSE_OR_POP;
3522 else
3523 jumpi = JUMP_IF_TRUE_OR_POP;
3524 end = compiler_new_block(c);
3525 if (end == NULL)
3526 return 0;
3527 s = e->v.BoolOp.values;
3528 n = asdl_seq_LEN(s) - 1;
3529 assert(n >= 0);
3530 for (i = 0; i < n; ++i) {
3531 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3532 ADDOP_JABS(c, jumpi, end);
3533 }
3534 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3535 compiler_use_next_block(c, end);
3536 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537}
3538
3539static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003540starunpack_helper(struct compiler *c, asdl_seq *elts,
3541 int single_op, int inner_op, int outer_op)
3542{
3543 Py_ssize_t n = asdl_seq_LEN(elts);
3544 Py_ssize_t i, nsubitems = 0, nseen = 0;
3545 for (i = 0; i < n; i++) {
3546 expr_ty elt = asdl_seq_GET(elts, i);
3547 if (elt->kind == Starred_kind) {
3548 if (nseen) {
3549 ADDOP_I(c, inner_op, nseen);
3550 nseen = 0;
3551 nsubitems++;
3552 }
3553 VISIT(c, expr, elt->v.Starred.value);
3554 nsubitems++;
3555 }
3556 else {
3557 VISIT(c, expr, elt);
3558 nseen++;
3559 }
3560 }
3561 if (nsubitems) {
3562 if (nseen) {
3563 ADDOP_I(c, inner_op, nseen);
3564 nsubitems++;
3565 }
3566 ADDOP_I(c, outer_op, nsubitems);
3567 }
3568 else
3569 ADDOP_I(c, single_op, nseen);
3570 return 1;
3571}
3572
3573static int
3574assignment_helper(struct compiler *c, asdl_seq *elts)
3575{
3576 Py_ssize_t n = asdl_seq_LEN(elts);
3577 Py_ssize_t i;
3578 int seen_star = 0;
3579 for (i = 0; i < n; i++) {
3580 expr_ty elt = asdl_seq_GET(elts, i);
3581 if (elt->kind == Starred_kind && !seen_star) {
3582 if ((i >= (1 << 8)) ||
3583 (n-i-1 >= (INT_MAX >> 8)))
3584 return compiler_error(c,
3585 "too many expressions in "
3586 "star-unpacking assignment");
3587 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3588 seen_star = 1;
3589 asdl_seq_SET(elts, i, elt->v.Starred.value);
3590 }
3591 else if (elt->kind == Starred_kind) {
3592 return compiler_error(c,
3593 "two starred expressions in assignment");
3594 }
3595 }
3596 if (!seen_star) {
3597 ADDOP_I(c, UNPACK_SEQUENCE, n);
3598 }
3599 VISIT_SEQ(c, expr, elts);
3600 return 1;
3601}
3602
3603static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604compiler_list(struct compiler *c, expr_ty e)
3605{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003606 asdl_seq *elts = e->v.List.elts;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003607 if (e->v.List.ctx == Store || e->v.List.ctx == NamedStore) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003608 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003610 else if (e->v.List.ctx == Load) {
3611 return starunpack_helper(c, elts,
3612 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003614 else
3615 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617}
3618
3619static int
3620compiler_tuple(struct compiler *c, expr_ty e)
3621{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003622 asdl_seq *elts = e->v.Tuple.elts;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003623 if (e->v.Tuple.ctx == Store || e->v.Tuple.ctx == NamedStore) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003624 return assignment_helper(c, elts);
3625 }
3626 else if (e->v.Tuple.ctx == Load) {
3627 return starunpack_helper(c, elts,
3628 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3629 }
3630 else
3631 VISIT_SEQ(c, expr, elts);
3632 return 1;
3633}
3634
3635static int
3636compiler_set(struct compiler *c, expr_ty e)
3637{
3638 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3639 BUILD_SET, BUILD_SET_UNPACK);
3640}
3641
3642static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003643are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3644{
3645 Py_ssize_t i;
3646 for (i = begin; i < end; i++) {
3647 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003648 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003649 return 0;
3650 }
3651 return 1;
3652}
3653
3654static int
3655compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3656{
3657 Py_ssize_t i, n = end - begin;
3658 PyObject *keys, *key;
3659 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3660 for (i = begin; i < end; i++) {
3661 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3662 }
3663 keys = PyTuple_New(n);
3664 if (keys == NULL) {
3665 return 0;
3666 }
3667 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003668 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003669 Py_INCREF(key);
3670 PyTuple_SET_ITEM(keys, i - begin, key);
3671 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003672 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003673 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3674 }
3675 else {
3676 for (i = begin; i < end; i++) {
3677 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3678 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3679 }
3680 ADDOP_I(c, BUILD_MAP, n);
3681 }
3682 return 1;
3683}
3684
3685static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003686compiler_dict(struct compiler *c, expr_ty e)
3687{
Victor Stinner976bb402016-03-23 11:36:19 +01003688 Py_ssize_t i, n, elements;
3689 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003690 int is_unpacking = 0;
3691 n = asdl_seq_LEN(e->v.Dict.values);
3692 containers = 0;
3693 elements = 0;
3694 for (i = 0; i < n; i++) {
3695 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3696 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003697 if (!compiler_subdict(c, e, i - elements, i))
3698 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003699 containers++;
3700 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003702 if (is_unpacking) {
3703 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3704 containers++;
3705 }
3706 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003707 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 }
3709 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003711 if (!compiler_subdict(c, e, n - elements, n))
3712 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003713 containers++;
3714 }
3715 /* If there is more than one dict, they need to be merged into a new
3716 * dict. If there is one dict and it's an unpacking, then it needs
3717 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003718 if (containers > 1 || is_unpacking) {
3719 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 }
3721 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722}
3723
3724static int
3725compiler_compare(struct compiler *c, expr_ty e)
3726{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003727 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003729 if (!check_compare(c, e)) {
3730 return 0;
3731 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003733 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3734 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3735 if (n == 0) {
3736 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3737 ADDOP_I(c, COMPARE_OP,
3738 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3739 }
3740 else {
3741 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (cleanup == NULL)
3743 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003744 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 VISIT(c, expr,
3746 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003747 ADDOP(c, DUP_TOP);
3748 ADDOP(c, ROT_THREE);
3749 ADDOP_I(c, COMPARE_OP,
3750 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3751 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3752 NEXT_BLOCK(c);
3753 }
3754 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3755 ADDOP_I(c, COMPARE_OP,
3756 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 basicblock *end = compiler_new_block(c);
3758 if (end == NULL)
3759 return 0;
3760 ADDOP_JREL(c, JUMP_FORWARD, end);
3761 compiler_use_next_block(c, cleanup);
3762 ADDOP(c, ROT_TWO);
3763 ADDOP(c, POP_TOP);
3764 compiler_use_next_block(c, end);
3765 }
3766 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767}
3768
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003769static PyTypeObject *
3770infer_type(expr_ty e)
3771{
3772 switch (e->kind) {
3773 case Tuple_kind:
3774 return &PyTuple_Type;
3775 case List_kind:
3776 case ListComp_kind:
3777 return &PyList_Type;
3778 case Dict_kind:
3779 case DictComp_kind:
3780 return &PyDict_Type;
3781 case Set_kind:
3782 case SetComp_kind:
3783 return &PySet_Type;
3784 case GeneratorExp_kind:
3785 return &PyGen_Type;
3786 case Lambda_kind:
3787 return &PyFunction_Type;
3788 case JoinedStr_kind:
3789 case FormattedValue_kind:
3790 return &PyUnicode_Type;
3791 case Constant_kind:
3792 return e->v.Constant.value->ob_type;
3793 default:
3794 return NULL;
3795 }
3796}
3797
3798static int
3799check_caller(struct compiler *c, expr_ty e)
3800{
3801 switch (e->kind) {
3802 case Constant_kind:
3803 case Tuple_kind:
3804 case List_kind:
3805 case ListComp_kind:
3806 case Dict_kind:
3807 case DictComp_kind:
3808 case Set_kind:
3809 case SetComp_kind:
3810 case GeneratorExp_kind:
3811 case JoinedStr_kind:
3812 case FormattedValue_kind:
3813 return compiler_warn(c, "'%.200s' object is not callable; "
3814 "perhaps you missed a comma?",
3815 infer_type(e)->tp_name);
3816 default:
3817 return 1;
3818 }
3819}
3820
3821static int
3822check_subscripter(struct compiler *c, expr_ty e)
3823{
3824 PyObject *v;
3825
3826 switch (e->kind) {
3827 case Constant_kind:
3828 v = e->v.Constant.value;
3829 if (!(v == Py_None || v == Py_Ellipsis ||
3830 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3831 PyAnySet_Check(v)))
3832 {
3833 return 1;
3834 }
3835 /* fall through */
3836 case Set_kind:
3837 case SetComp_kind:
3838 case GeneratorExp_kind:
3839 case Lambda_kind:
3840 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3841 "perhaps you missed a comma?",
3842 infer_type(e)->tp_name);
3843 default:
3844 return 1;
3845 }
3846}
3847
3848static int
3849check_index(struct compiler *c, expr_ty e, slice_ty s)
3850{
3851 PyObject *v;
3852
3853 if (s->kind != Index_kind) {
3854 return 1;
3855 }
3856 PyTypeObject *index_type = infer_type(s->v.Index.value);
3857 if (index_type == NULL
3858 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3859 || index_type == &PySlice_Type) {
3860 return 1;
3861 }
3862
3863 switch (e->kind) {
3864 case Constant_kind:
3865 v = e->v.Constant.value;
3866 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3867 return 1;
3868 }
3869 /* fall through */
3870 case Tuple_kind:
3871 case List_kind:
3872 case ListComp_kind:
3873 case JoinedStr_kind:
3874 case FormattedValue_kind:
3875 return compiler_warn(c, "%.200s indices must be integers or slices, "
3876 "not %.200s; "
3877 "perhaps you missed a comma?",
3878 infer_type(e)->tp_name,
3879 index_type->tp_name);
3880 default:
3881 return 1;
3882 }
3883}
3884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003886maybe_optimize_method_call(struct compiler *c, expr_ty e)
3887{
3888 Py_ssize_t argsl, i;
3889 expr_ty meth = e->v.Call.func;
3890 asdl_seq *args = e->v.Call.args;
3891
3892 /* Check that the call node is an attribute access, and that
3893 the call doesn't have keyword parameters. */
3894 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3895 asdl_seq_LEN(e->v.Call.keywords))
3896 return -1;
3897
3898 /* Check that there are no *varargs types of arguments. */
3899 argsl = asdl_seq_LEN(args);
3900 for (i = 0; i < argsl; i++) {
3901 expr_ty elt = asdl_seq_GET(args, i);
3902 if (elt->kind == Starred_kind) {
3903 return -1;
3904 }
3905 }
3906
3907 /* Alright, we can optimize the code. */
3908 VISIT(c, expr, meth->v.Attribute.value);
3909 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3910 VISIT_SEQ(c, expr, e->v.Call.args);
3911 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3912 return 1;
3913}
3914
3915static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916compiler_call(struct compiler *c, expr_ty e)
3917{
Yury Selivanovf2392132016-12-13 19:03:51 -05003918 if (maybe_optimize_method_call(c, e) > 0)
3919 return 1;
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003920 if (!check_caller(c, e->v.Call.func)) {
3921 return 0;
3922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 VISIT(c, expr, e->v.Call.func);
3924 return compiler_call_helper(c, 0,
3925 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003926 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003927}
3928
Eric V. Smith235a6f02015-09-19 14:51:32 -04003929static int
3930compiler_joined_str(struct compiler *c, expr_ty e)
3931{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003932 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003933 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3934 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003935 return 1;
3936}
3937
Eric V. Smitha78c7952015-11-03 12:45:05 -05003938/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003939static int
3940compiler_formatted_value(struct compiler *c, expr_ty e)
3941{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003942 /* Our oparg encodes 2 pieces of information: the conversion
3943 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003944
Eric V. Smitha78c7952015-11-03 12:45:05 -05003945 Convert the conversion char to 2 bits:
3946 None: 000 0x0 FVC_NONE
3947 !s : 001 0x1 FVC_STR
3948 !r : 010 0x2 FVC_REPR
3949 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003950
Eric V. Smitha78c7952015-11-03 12:45:05 -05003951 next bit is whether or not we have a format spec:
3952 yes : 100 0x4
3953 no : 000 0x0
3954 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003955
Eric V. Smitha78c7952015-11-03 12:45:05 -05003956 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003957
Eric V. Smitha78c7952015-11-03 12:45:05 -05003958 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003959 VISIT(c, expr, e->v.FormattedValue.value);
3960
Eric V. Smitha78c7952015-11-03 12:45:05 -05003961 switch (e->v.FormattedValue.conversion) {
3962 case 's': oparg = FVC_STR; break;
3963 case 'r': oparg = FVC_REPR; break;
3964 case 'a': oparg = FVC_ASCII; break;
3965 case -1: oparg = FVC_NONE; break;
3966 default:
3967 PyErr_SetString(PyExc_SystemError,
3968 "Unrecognized conversion character");
3969 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003970 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003971 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003972 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003973 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003974 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003975 }
3976
Eric V. Smitha78c7952015-11-03 12:45:05 -05003977 /* And push our opcode and oparg */
3978 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003979 return 1;
3980}
3981
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003982static int
3983compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3984{
3985 Py_ssize_t i, n = end - begin;
3986 keyword_ty kw;
3987 PyObject *keys, *key;
3988 assert(n > 0);
3989 if (n > 1) {
3990 for (i = begin; i < end; i++) {
3991 kw = asdl_seq_GET(keywords, i);
3992 VISIT(c, expr, kw->value);
3993 }
3994 keys = PyTuple_New(n);
3995 if (keys == NULL) {
3996 return 0;
3997 }
3998 for (i = begin; i < end; i++) {
3999 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4000 Py_INCREF(key);
4001 PyTuple_SET_ITEM(keys, i - begin, key);
4002 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004003 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004004 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4005 }
4006 else {
4007 /* a for loop only executes once */
4008 for (i = begin; i < end; i++) {
4009 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004010 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004011 VISIT(c, expr, kw->value);
4012 }
4013 ADDOP_I(c, BUILD_MAP, n);
4014 }
4015 return 1;
4016}
4017
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004018/* shared code between compiler_call and compiler_class */
4019static int
4020compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004021 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004022 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004023 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004024{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004025 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004026 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004027
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004028 /* the number of tuples and dictionaries on the stack */
4029 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4030
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004031 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004032 nkwelts = asdl_seq_LEN(keywords);
4033
4034 for (i = 0; i < nkwelts; i++) {
4035 keyword_ty kw = asdl_seq_GET(keywords, i);
4036 if (kw->arg == NULL) {
4037 mustdictunpack = 1;
4038 break;
4039 }
4040 }
4041
4042 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004043 for (i = 0; i < nelts; i++) {
4044 expr_ty elt = asdl_seq_GET(args, i);
4045 if (elt->kind == Starred_kind) {
4046 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004047 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004048 if (nseen) {
4049 ADDOP_I(c, BUILD_TUPLE, nseen);
4050 nseen = 0;
4051 nsubargs++;
4052 }
4053 VISIT(c, expr, elt->v.Starred.value);
4054 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004055 }
4056 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004057 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004058 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004059 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004061
4062 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004063 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004064 if (nseen) {
4065 /* Pack up any trailing positional arguments. */
4066 ADDOP_I(c, BUILD_TUPLE, nseen);
4067 nsubargs++;
4068 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004069 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004070 /* If we ended up with more than one stararg, we need
4071 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004072 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004073 }
4074 else if (nsubargs == 0) {
4075 ADDOP_I(c, BUILD_TUPLE, 0);
4076 }
4077 nseen = 0; /* the number of keyword arguments on the stack following */
4078 for (i = 0; i < nkwelts; i++) {
4079 keyword_ty kw = asdl_seq_GET(keywords, i);
4080 if (kw->arg == NULL) {
4081 /* A keyword argument unpacking. */
4082 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004083 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4084 return 0;
4085 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004086 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004087 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004088 VISIT(c, expr, kw->value);
4089 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004090 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004091 else {
4092 nseen++;
4093 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004094 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004095 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004096 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004097 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004098 return 0;
4099 nsubkwargs++;
4100 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004101 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004102 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004103 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004104 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004105 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4106 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004108 else if (nkwelts) {
4109 PyObject *names;
4110 VISIT_SEQ(c, keyword, keywords);
4111 names = PyTuple_New(nkwelts);
4112 if (names == NULL) {
4113 return 0;
4114 }
4115 for (i = 0; i < nkwelts; i++) {
4116 keyword_ty kw = asdl_seq_GET(keywords, i);
4117 Py_INCREF(kw->arg);
4118 PyTuple_SET_ITEM(names, i, kw->arg);
4119 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004120 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004121 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004124 else {
4125 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4126 return 1;
4127 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128}
4129
Nick Coghlan650f0d02007-04-15 12:05:43 +00004130
4131/* List and set comprehensions and generator expressions work by creating a
4132 nested function to perform the actual iteration. This means that the
4133 iteration variables don't leak into the current scope.
4134 The defined function is called immediately following its definition, with the
4135 result of that call being the result of the expression.
4136 The LC/SC version returns the populated container, while the GE version is
4137 flagged in symtable.c as a generator, so it returns the generator object
4138 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004139
4140 Possible cleanups:
4141 - iterate over the generator sequence instead of using recursion
4142*/
4143
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146compiler_comprehension_generator(struct compiler *c,
4147 asdl_seq *generators, int gen_index,
4148 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004150 comprehension_ty gen;
4151 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4152 if (gen->is_async) {
4153 return compiler_async_comprehension_generator(
4154 c, generators, gen_index, elt, val, type);
4155 } else {
4156 return compiler_sync_comprehension_generator(
4157 c, generators, gen_index, elt, val, type);
4158 }
4159}
4160
4161static int
4162compiler_sync_comprehension_generator(struct compiler *c,
4163 asdl_seq *generators, int gen_index,
4164 expr_ty elt, expr_ty val, int type)
4165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* generate code for the iterator, then each of the ifs,
4167 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 comprehension_ty gen;
4170 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004171 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 start = compiler_new_block(c);
4174 skip = compiler_new_block(c);
4175 if_cleanup = compiler_new_block(c);
4176 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4179 anchor == NULL)
4180 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (gen_index == 0) {
4185 /* Receive outermost iter as an implicit argument */
4186 c->u->u_argcount = 1;
4187 ADDOP_I(c, LOAD_FAST, 0);
4188 }
4189 else {
4190 /* Sub-iter - calculate on the fly */
4191 VISIT(c, expr, gen->iter);
4192 ADDOP(c, GET_ITER);
4193 }
4194 compiler_use_next_block(c, start);
4195 ADDOP_JREL(c, FOR_ITER, anchor);
4196 NEXT_BLOCK(c);
4197 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 /* XXX this needs to be cleaned up...a lot! */
4200 n = asdl_seq_LEN(gen->ifs);
4201 for (i = 0; i < n; i++) {
4202 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004203 if (!compiler_jump_if(c, e, if_cleanup, 0))
4204 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 NEXT_BLOCK(c);
4206 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 if (++gen_index < asdl_seq_LEN(generators))
4209 if (!compiler_comprehension_generator(c,
4210 generators, gen_index,
4211 elt, val, type))
4212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 /* only append after the last for generator */
4215 if (gen_index >= asdl_seq_LEN(generators)) {
4216 /* comprehension specific code */
4217 switch (type) {
4218 case COMP_GENEXP:
4219 VISIT(c, expr, elt);
4220 ADDOP(c, YIELD_VALUE);
4221 ADDOP(c, POP_TOP);
4222 break;
4223 case COMP_LISTCOMP:
4224 VISIT(c, expr, elt);
4225 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4226 break;
4227 case COMP_SETCOMP:
4228 VISIT(c, expr, elt);
4229 ADDOP_I(c, SET_ADD, gen_index + 1);
4230 break;
4231 case COMP_DICTCOMP:
4232 /* With 'd[k] = v', v is evaluated before k, so we do
4233 the same. */
4234 VISIT(c, expr, val);
4235 VISIT(c, expr, elt);
4236 ADDOP_I(c, MAP_ADD, gen_index + 1);
4237 break;
4238 default:
4239 return 0;
4240 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 compiler_use_next_block(c, skip);
4243 }
4244 compiler_use_next_block(c, if_cleanup);
4245 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4246 compiler_use_next_block(c, anchor);
4247
4248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249}
4250
4251static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004252compiler_async_comprehension_generator(struct compiler *c,
4253 asdl_seq *generators, int gen_index,
4254 expr_ty elt, expr_ty val, int type)
4255{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004256 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004257 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004258 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004259 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004260 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004261 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004262
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004263 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004264 return 0;
4265 }
4266
4267 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4268
4269 if (gen_index == 0) {
4270 /* Receive outermost iter as an implicit argument */
4271 c->u->u_argcount = 1;
4272 ADDOP_I(c, LOAD_FAST, 0);
4273 }
4274 else {
4275 /* Sub-iter - calculate on the fly */
4276 VISIT(c, expr, gen->iter);
4277 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004278 }
4279
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004280 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004281
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004282 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004283 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004284 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004285 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004286 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004287 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004288
4289 n = asdl_seq_LEN(gen->ifs);
4290 for (i = 0; i < n; i++) {
4291 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004292 if (!compiler_jump_if(c, e, if_cleanup, 0))
4293 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004294 NEXT_BLOCK(c);
4295 }
4296
4297 if (++gen_index < asdl_seq_LEN(generators))
4298 if (!compiler_comprehension_generator(c,
4299 generators, gen_index,
4300 elt, val, type))
4301 return 0;
4302
4303 /* only append after the last for generator */
4304 if (gen_index >= asdl_seq_LEN(generators)) {
4305 /* comprehension specific code */
4306 switch (type) {
4307 case COMP_GENEXP:
4308 VISIT(c, expr, elt);
4309 ADDOP(c, YIELD_VALUE);
4310 ADDOP(c, POP_TOP);
4311 break;
4312 case COMP_LISTCOMP:
4313 VISIT(c, expr, elt);
4314 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4315 break;
4316 case COMP_SETCOMP:
4317 VISIT(c, expr, elt);
4318 ADDOP_I(c, SET_ADD, gen_index + 1);
4319 break;
4320 case COMP_DICTCOMP:
4321 /* With 'd[k] = v', v is evaluated before k, so we do
4322 the same. */
4323 VISIT(c, expr, val);
4324 VISIT(c, expr, elt);
4325 ADDOP_I(c, MAP_ADD, gen_index + 1);
4326 break;
4327 default:
4328 return 0;
4329 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004330 }
4331 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004332 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4333
4334 compiler_use_next_block(c, except);
4335 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004336
4337 return 1;
4338}
4339
4340static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004341compiler_comprehension(struct compiler *c, expr_ty e, int type,
4342 identifier name, asdl_seq *generators, expr_ty elt,
4343 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004346 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004347 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004348 int is_async_function = c->u->u_ste->ste_coroutine;
4349 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004350
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004351 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004352
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004353 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4354 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004357 }
4358
4359 is_async_generator = c->u->u_ste->ste_coroutine;
4360
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004361 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 compiler_error(c, "asynchronous comprehension outside of "
4363 "an asynchronous function");
4364 goto error_in_scope;
4365 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 if (type != COMP_GENEXP) {
4368 int op;
4369 switch (type) {
4370 case COMP_LISTCOMP:
4371 op = BUILD_LIST;
4372 break;
4373 case COMP_SETCOMP:
4374 op = BUILD_SET;
4375 break;
4376 case COMP_DICTCOMP:
4377 op = BUILD_MAP;
4378 break;
4379 default:
4380 PyErr_Format(PyExc_SystemError,
4381 "unknown comprehension type %d", type);
4382 goto error_in_scope;
4383 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 ADDOP_I(c, op, 0);
4386 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 if (!compiler_comprehension_generator(c, generators, 0, elt,
4389 val, type))
4390 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 if (type != COMP_GENEXP) {
4393 ADDOP(c, RETURN_VALUE);
4394 }
4395
4396 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004397 qualname = c->u->u_qualname;
4398 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004400 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 goto error;
4402
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004403 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004405 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 Py_DECREF(co);
4407
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004408 VISIT(c, expr, outermost->iter);
4409
4410 if (outermost->is_async) {
4411 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004412 } else {
4413 ADDOP(c, GET_ITER);
4414 }
4415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004417
4418 if (is_async_generator && type != COMP_GENEXP) {
4419 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004420 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004421 ADDOP(c, YIELD_FROM);
4422 }
4423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004425error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004427error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004428 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 Py_XDECREF(co);
4430 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004431}
4432
4433static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434compiler_genexp(struct compiler *c, expr_ty e)
4435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 static identifier name;
4437 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004438 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if (!name)
4440 return 0;
4441 }
4442 assert(e->kind == GeneratorExp_kind);
4443 return compiler_comprehension(c, e, COMP_GENEXP, name,
4444 e->v.GeneratorExp.generators,
4445 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446}
4447
4448static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004449compiler_listcomp(struct compiler *c, expr_ty e)
4450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 static identifier name;
4452 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004453 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 if (!name)
4455 return 0;
4456 }
4457 assert(e->kind == ListComp_kind);
4458 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4459 e->v.ListComp.generators,
4460 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004461}
4462
4463static int
4464compiler_setcomp(struct compiler *c, expr_ty e)
4465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 static identifier name;
4467 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004468 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 if (!name)
4470 return 0;
4471 }
4472 assert(e->kind == SetComp_kind);
4473 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4474 e->v.SetComp.generators,
4475 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004476}
4477
4478
4479static int
4480compiler_dictcomp(struct compiler *c, expr_ty e)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 static identifier name;
4483 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004484 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (!name)
4486 return 0;
4487 }
4488 assert(e->kind == DictComp_kind);
4489 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4490 e->v.DictComp.generators,
4491 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004492}
4493
4494
4495static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004496compiler_visit_keyword(struct compiler *c, keyword_ty k)
4497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 VISIT(c, expr, k->value);
4499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004503 whether they are true or false.
4504
4505 Return values: 1 for true, 0 for false, -1 for non-constant.
4506 */
4507
4508static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004509expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004510{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004511 if (e->kind == Constant_kind) {
4512 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004513 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004514 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004515}
4516
Yury Selivanov75445082015-05-11 22:57:16 -04004517
4518/*
4519 Implements the async with statement.
4520
4521 The semantics outlined in that PEP are as follows:
4522
4523 async with EXPR as VAR:
4524 BLOCK
4525
4526 It is implemented roughly as:
4527
4528 context = EXPR
4529 exit = context.__aexit__ # not calling it
4530 value = await context.__aenter__()
4531 try:
4532 VAR = value # if VAR present in the syntax
4533 BLOCK
4534 finally:
4535 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004536 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004537 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004538 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004539 if not (await exit(*exc)):
4540 raise
4541 */
4542static int
4543compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4544{
4545 basicblock *block, *finally;
4546 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4547
4548 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004549 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4550 return compiler_error(c, "'async with' outside async function");
4551 }
Yury Selivanov75445082015-05-11 22:57:16 -04004552
4553 block = compiler_new_block(c);
4554 finally = compiler_new_block(c);
4555 if (!block || !finally)
4556 return 0;
4557
4558 /* Evaluate EXPR */
4559 VISIT(c, expr, item->context_expr);
4560
4561 ADDOP(c, BEFORE_ASYNC_WITH);
4562 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004563 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004564 ADDOP(c, YIELD_FROM);
4565
4566 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4567
4568 /* SETUP_ASYNC_WITH pushes a finally block. */
4569 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004570 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004571 return 0;
4572 }
4573
4574 if (item->optional_vars) {
4575 VISIT(c, expr, item->optional_vars);
4576 }
4577 else {
4578 /* Discard result from context.__aenter__() */
4579 ADDOP(c, POP_TOP);
4580 }
4581
4582 pos++;
4583 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4584 /* BLOCK code */
4585 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4586 else if (!compiler_async_with(c, s, pos))
4587 return 0;
4588
4589 /* End of try block; start the finally block */
4590 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004591 ADDOP(c, BEGIN_FINALLY);
4592 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004593
Yury Selivanov75445082015-05-11 22:57:16 -04004594 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004595 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004596 return 0;
4597
4598 /* Finally block starts; context.__exit__ is on the stack under
4599 the exception or return information. Just issue our magic
4600 opcode. */
4601 ADDOP(c, WITH_CLEANUP_START);
4602
4603 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004604 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004605 ADDOP(c, YIELD_FROM);
4606
4607 ADDOP(c, WITH_CLEANUP_FINISH);
4608
4609 /* Finally block ends. */
4610 ADDOP(c, END_FINALLY);
4611 compiler_pop_fblock(c, FINALLY_END, finally);
4612 return 1;
4613}
4614
4615
Guido van Rossumc2e20742006-02-27 22:32:47 +00004616/*
4617 Implements the with statement from PEP 343.
4618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004620
4621 with EXPR as VAR:
4622 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623
Guido van Rossumc2e20742006-02-27 22:32:47 +00004624 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625
Thomas Wouters477c8d52006-05-27 19:21:47 +00004626 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004627 exit = context.__exit__ # not calling it
4628 value = context.__enter__()
4629 try:
4630 VAR = value # if VAR present in the syntax
4631 BLOCK
4632 finally:
4633 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004634 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004635 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004636 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004637 exit(*exc)
4638 */
4639static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004640compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004641{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004642 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004643 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004644
4645 assert(s->kind == With_kind);
4646
Guido van Rossumc2e20742006-02-27 22:32:47 +00004647 block = compiler_new_block(c);
4648 finally = compiler_new_block(c);
4649 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004650 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004651
Thomas Wouters477c8d52006-05-27 19:21:47 +00004652 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004653 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004654 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004655
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004656 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004657 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004658 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004659 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004660 }
4661
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004662 if (item->optional_vars) {
4663 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004664 }
4665 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004667 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004668 }
4669
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004670 pos++;
4671 if (pos == asdl_seq_LEN(s->v.With.items))
4672 /* BLOCK code */
4673 VISIT_SEQ(c, stmt, s->v.With.body)
4674 else if (!compiler_with(c, s, pos))
4675 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004676
4677 /* End of try block; start the finally block */
4678 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004679 ADDOP(c, BEGIN_FINALLY);
4680 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004681
Guido van Rossumc2e20742006-02-27 22:32:47 +00004682 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004683 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004684 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004685
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004686 /* Finally block starts; context.__exit__ is on the stack under
4687 the exception or return information. Just issue our magic
4688 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004689 ADDOP(c, WITH_CLEANUP_START);
4690 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004691
4692 /* Finally block ends. */
4693 ADDOP(c, END_FINALLY);
4694 compiler_pop_fblock(c, FINALLY_END, finally);
4695 return 1;
4696}
4697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004699compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004702 case NamedExpr_kind:
4703 VISIT(c, expr, e->v.NamedExpr.value);
4704 ADDOP(c, DUP_TOP);
4705 VISIT(c, expr, e->v.NamedExpr.target);
4706 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 case BoolOp_kind:
4708 return compiler_boolop(c, e);
4709 case BinOp_kind:
4710 VISIT(c, expr, e->v.BinOp.left);
4711 VISIT(c, expr, e->v.BinOp.right);
4712 ADDOP(c, binop(c, e->v.BinOp.op));
4713 break;
4714 case UnaryOp_kind:
4715 VISIT(c, expr, e->v.UnaryOp.operand);
4716 ADDOP(c, unaryop(e->v.UnaryOp.op));
4717 break;
4718 case Lambda_kind:
4719 return compiler_lambda(c, e);
4720 case IfExp_kind:
4721 return compiler_ifexp(c, e);
4722 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004723 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004725 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 case GeneratorExp_kind:
4727 return compiler_genexp(c, e);
4728 case ListComp_kind:
4729 return compiler_listcomp(c, e);
4730 case SetComp_kind:
4731 return compiler_setcomp(c, e);
4732 case DictComp_kind:
4733 return compiler_dictcomp(c, e);
4734 case Yield_kind:
4735 if (c->u->u_ste->ste_type != FunctionBlock)
4736 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004737 if (e->v.Yield.value) {
4738 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 }
4740 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004741 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004743 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004745 case YieldFrom_kind:
4746 if (c->u->u_ste->ste_type != FunctionBlock)
4747 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004748
4749 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4750 return compiler_error(c, "'yield from' inside async function");
4751
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004752 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004753 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004754 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004755 ADDOP(c, YIELD_FROM);
4756 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004757 case Await_kind:
4758 if (c->u->u_ste->ste_type != FunctionBlock)
4759 return compiler_error(c, "'await' outside function");
4760
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004761 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4762 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004763 return compiler_error(c, "'await' outside async function");
4764
4765 VISIT(c, expr, e->v.Await.value);
4766 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004767 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004768 ADDOP(c, YIELD_FROM);
4769 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 case Compare_kind:
4771 return compiler_compare(c, e);
4772 case Call_kind:
4773 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004774 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004775 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004776 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004777 case JoinedStr_kind:
4778 return compiler_joined_str(c, e);
4779 case FormattedValue_kind:
4780 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 /* The following exprs can be assignment targets. */
4782 case Attribute_kind:
4783 if (e->v.Attribute.ctx != AugStore)
4784 VISIT(c, expr, e->v.Attribute.value);
4785 switch (e->v.Attribute.ctx) {
4786 case AugLoad:
4787 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004788 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 case Load:
4790 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4791 break;
4792 case AugStore:
4793 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004794 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 case Store:
4796 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4797 break;
4798 case Del:
4799 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4800 break;
4801 case Param:
4802 default:
4803 PyErr_SetString(PyExc_SystemError,
4804 "param invalid in attribute expression");
4805 return 0;
4806 }
4807 break;
4808 case Subscript_kind:
4809 switch (e->v.Subscript.ctx) {
4810 case AugLoad:
4811 VISIT(c, expr, e->v.Subscript.value);
4812 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4813 break;
4814 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004815 if (!check_subscripter(c, e->v.Subscript.value)) {
4816 return 0;
4817 }
4818 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4819 return 0;
4820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 VISIT(c, expr, e->v.Subscript.value);
4822 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4823 break;
4824 case AugStore:
4825 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4826 break;
4827 case Store:
4828 VISIT(c, expr, e->v.Subscript.value);
4829 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4830 break;
4831 case Del:
4832 VISIT(c, expr, e->v.Subscript.value);
4833 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4834 break;
4835 case Param:
4836 default:
4837 PyErr_SetString(PyExc_SystemError,
4838 "param invalid in subscript expression");
4839 return 0;
4840 }
4841 break;
4842 case Starred_kind:
4843 switch (e->v.Starred.ctx) {
4844 case Store:
4845 /* In all legitimate cases, the Starred node was already replaced
4846 * by compiler_list/compiler_tuple. XXX: is that okay? */
4847 return compiler_error(c,
4848 "starred assignment target must be in a list or tuple");
4849 default:
4850 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004851 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 }
4853 break;
4854 case Name_kind:
4855 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4856 /* child nodes of List and Tuple will have expr_context set */
4857 case List_kind:
4858 return compiler_list(c, e);
4859 case Tuple_kind:
4860 return compiler_tuple(c, e);
4861 }
4862 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004863}
4864
4865static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004866compiler_visit_expr(struct compiler *c, expr_ty e)
4867{
4868 /* If expr e has a different line number than the last expr/stmt,
4869 set a new line number for the next instruction.
4870 */
4871 int old_lineno = c->u->u_lineno;
4872 int old_col_offset = c->u->u_col_offset;
4873 if (e->lineno != c->u->u_lineno) {
4874 c->u->u_lineno = e->lineno;
4875 c->u->u_lineno_set = 0;
4876 }
4877 /* Updating the column offset is always harmless. */
4878 c->u->u_col_offset = e->col_offset;
4879
4880 int res = compiler_visit_expr1(c, e);
4881
4882 if (old_lineno != c->u->u_lineno) {
4883 c->u->u_lineno = old_lineno;
4884 c->u->u_lineno_set = 0;
4885 }
4886 c->u->u_col_offset = old_col_offset;
4887 return res;
4888}
4889
4890static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891compiler_augassign(struct compiler *c, stmt_ty s)
4892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 expr_ty e = s->v.AugAssign.target;
4894 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 switch (e->kind) {
4899 case Attribute_kind:
4900 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004901 AugLoad, e->lineno, e->col_offset,
4902 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 if (auge == NULL)
4904 return 0;
4905 VISIT(c, expr, auge);
4906 VISIT(c, expr, s->v.AugAssign.value);
4907 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4908 auge->v.Attribute.ctx = AugStore;
4909 VISIT(c, expr, auge);
4910 break;
4911 case Subscript_kind:
4912 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004913 AugLoad, e->lineno, e->col_offset,
4914 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 if (auge == NULL)
4916 return 0;
4917 VISIT(c, expr, auge);
4918 VISIT(c, expr, s->v.AugAssign.value);
4919 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4920 auge->v.Subscript.ctx = AugStore;
4921 VISIT(c, expr, auge);
4922 break;
4923 case Name_kind:
4924 if (!compiler_nameop(c, e->v.Name.id, Load))
4925 return 0;
4926 VISIT(c, expr, s->v.AugAssign.value);
4927 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4928 return compiler_nameop(c, e->v.Name.id, Store);
4929 default:
4930 PyErr_Format(PyExc_SystemError,
4931 "invalid node type (%d) for augmented assignment",
4932 e->kind);
4933 return 0;
4934 }
4935 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004936}
4937
4938static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004939check_ann_expr(struct compiler *c, expr_ty e)
4940{
4941 VISIT(c, expr, e);
4942 ADDOP(c, POP_TOP);
4943 return 1;
4944}
4945
4946static int
4947check_annotation(struct compiler *c, stmt_ty s)
4948{
4949 /* Annotations are only evaluated in a module or class. */
4950 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4951 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4952 return check_ann_expr(c, s->v.AnnAssign.annotation);
4953 }
4954 return 1;
4955}
4956
4957static int
4958check_ann_slice(struct compiler *c, slice_ty sl)
4959{
4960 switch(sl->kind) {
4961 case Index_kind:
4962 return check_ann_expr(c, sl->v.Index.value);
4963 case Slice_kind:
4964 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4965 return 0;
4966 }
4967 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4968 return 0;
4969 }
4970 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4971 return 0;
4972 }
4973 break;
4974 default:
4975 PyErr_SetString(PyExc_SystemError,
4976 "unexpected slice kind");
4977 return 0;
4978 }
4979 return 1;
4980}
4981
4982static int
4983check_ann_subscr(struct compiler *c, slice_ty sl)
4984{
4985 /* We check that everything in a subscript is defined at runtime. */
4986 Py_ssize_t i, n;
4987
4988 switch (sl->kind) {
4989 case Index_kind:
4990 case Slice_kind:
4991 if (!check_ann_slice(c, sl)) {
4992 return 0;
4993 }
4994 break;
4995 case ExtSlice_kind:
4996 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4997 for (i = 0; i < n; i++) {
4998 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4999 switch (subsl->kind) {
5000 case Index_kind:
5001 case Slice_kind:
5002 if (!check_ann_slice(c, subsl)) {
5003 return 0;
5004 }
5005 break;
5006 case ExtSlice_kind:
5007 default:
5008 PyErr_SetString(PyExc_SystemError,
5009 "extended slice invalid in nested slice");
5010 return 0;
5011 }
5012 }
5013 break;
5014 default:
5015 PyErr_Format(PyExc_SystemError,
5016 "invalid subscript kind %d", sl->kind);
5017 return 0;
5018 }
5019 return 1;
5020}
5021
5022static int
5023compiler_annassign(struct compiler *c, stmt_ty s)
5024{
5025 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005026 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005027
5028 assert(s->kind == AnnAssign_kind);
5029
5030 /* We perform the actual assignment first. */
5031 if (s->v.AnnAssign.value) {
5032 VISIT(c, expr, s->v.AnnAssign.value);
5033 VISIT(c, expr, targ);
5034 }
5035 switch (targ->kind) {
5036 case Name_kind:
5037 /* If we have a simple name in a module or class, store annotation. */
5038 if (s->v.AnnAssign.simple &&
5039 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5040 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005041 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5042 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5043 }
5044 else {
5045 VISIT(c, expr, s->v.AnnAssign.annotation);
5046 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005047 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005048 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005050 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005051 }
5052 break;
5053 case Attribute_kind:
5054 if (!s->v.AnnAssign.value &&
5055 !check_ann_expr(c, targ->v.Attribute.value)) {
5056 return 0;
5057 }
5058 break;
5059 case Subscript_kind:
5060 if (!s->v.AnnAssign.value &&
5061 (!check_ann_expr(c, targ->v.Subscript.value) ||
5062 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5063 return 0;
5064 }
5065 break;
5066 default:
5067 PyErr_Format(PyExc_SystemError,
5068 "invalid node type (%d) for annotated assignment",
5069 targ->kind);
5070 return 0;
5071 }
5072 /* Annotation is evaluated last. */
5073 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5074 return 0;
5075 }
5076 return 1;
5077}
5078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005079/* Raises a SyntaxError and returns 0.
5080 If something goes wrong, a different exception may be raised.
5081*/
5082
5083static int
5084compiler_error(struct compiler *c, const char *errstr)
5085{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005086 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005088
Victor Stinner14e461d2013-08-26 22:28:21 +02005089 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 if (!loc) {
5091 Py_INCREF(Py_None);
5092 loc = Py_None;
5093 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005094 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005095 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 if (!u)
5097 goto exit;
5098 v = Py_BuildValue("(zO)", errstr, u);
5099 if (!v)
5100 goto exit;
5101 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 Py_DECREF(loc);
5104 Py_XDECREF(u);
5105 Py_XDECREF(v);
5106 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107}
5108
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005109/* Emits a SyntaxWarning and returns 1 on success.
5110 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5111 and returns 0.
5112*/
5113static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005114compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005115{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005116 va_list vargs;
5117#ifdef HAVE_STDARG_PROTOTYPES
5118 va_start(vargs, format);
5119#else
5120 va_start(vargs);
5121#endif
5122 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5123 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005124 if (msg == NULL) {
5125 return 0;
5126 }
5127 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5128 c->u->u_lineno, NULL, NULL) < 0)
5129 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005130 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005131 /* Replace the SyntaxWarning exception with a SyntaxError
5132 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005133 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005134 assert(PyUnicode_AsUTF8(msg) != NULL);
5135 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005136 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005137 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005138 return 0;
5139 }
5140 Py_DECREF(msg);
5141 return 1;
5142}
5143
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005144static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145compiler_handle_subscr(struct compiler *c, const char *kind,
5146 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 /* XXX this code is duplicated */
5151 switch (ctx) {
5152 case AugLoad: /* fall through to Load */
5153 case Load: op = BINARY_SUBSCR; break;
5154 case AugStore:/* fall through to Store */
5155 case Store: op = STORE_SUBSCR; break;
5156 case Del: op = DELETE_SUBSCR; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005157 case NamedStore:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 case Param:
5159 PyErr_Format(PyExc_SystemError,
5160 "invalid %s kind %d in subscript\n",
5161 kind, ctx);
5162 return 0;
5163 }
5164 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005165 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 }
5167 else if (ctx == AugStore) {
5168 ADDOP(c, ROT_THREE);
5169 }
5170 ADDOP(c, op);
5171 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005172}
5173
5174static int
5175compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 int n = 2;
5178 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 /* only handles the cases where BUILD_SLICE is emitted */
5181 if (s->v.Slice.lower) {
5182 VISIT(c, expr, s->v.Slice.lower);
5183 }
5184 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005185 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 if (s->v.Slice.upper) {
5189 VISIT(c, expr, s->v.Slice.upper);
5190 }
5191 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005192 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 }
5194
5195 if (s->v.Slice.step) {
5196 n++;
5197 VISIT(c, expr, s->v.Slice.step);
5198 }
5199 ADDOP_I(c, BUILD_SLICE, n);
5200 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005201}
5202
5203static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5205 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 switch (s->kind) {
5208 case Slice_kind:
5209 return compiler_slice(c, s, ctx);
5210 case Index_kind:
5211 VISIT(c, expr, s->v.Index.value);
5212 break;
5213 case ExtSlice_kind:
5214 default:
5215 PyErr_SetString(PyExc_SystemError,
5216 "extended slice invalid in nested slice");
5217 return 0;
5218 }
5219 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220}
5221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005222static int
5223compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5224{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005225 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 switch (s->kind) {
5227 case Index_kind:
5228 kindname = "index";
5229 if (ctx != AugStore) {
5230 VISIT(c, expr, s->v.Index.value);
5231 }
5232 break;
5233 case Slice_kind:
5234 kindname = "slice";
5235 if (ctx != AugStore) {
5236 if (!compiler_slice(c, s, ctx))
5237 return 0;
5238 }
5239 break;
5240 case ExtSlice_kind:
5241 kindname = "extended slice";
5242 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005243 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 for (i = 0; i < n; i++) {
5245 slice_ty sub = (slice_ty)asdl_seq_GET(
5246 s->v.ExtSlice.dims, i);
5247 if (!compiler_visit_nested_slice(c, sub, ctx))
5248 return 0;
5249 }
5250 ADDOP_I(c, BUILD_TUPLE, n);
5251 }
5252 break;
5253 default:
5254 PyErr_Format(PyExc_SystemError,
5255 "invalid subscript kind %d", s->kind);
5256 return 0;
5257 }
5258 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005259}
5260
Thomas Wouters89f507f2006-12-13 04:49:30 +00005261/* End of the compiler section, beginning of the assembler section */
5262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005263/* do depth-first search of basic block graph, starting with block.
5264 post records the block indices in post-order.
5265
5266 XXX must handle implicit jumps from one block to next
5267*/
5268
Thomas Wouters89f507f2006-12-13 04:49:30 +00005269struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 PyObject *a_bytecode; /* string containing bytecode */
5271 int a_offset; /* offset into bytecode */
5272 int a_nblocks; /* number of reachable blocks */
5273 basicblock **a_postorder; /* list of blocks in dfs postorder */
5274 PyObject *a_lnotab; /* string containing lnotab */
5275 int a_lnotab_off; /* offset into lnotab */
5276 int a_lineno; /* last lineno of emitted instruction */
5277 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005278};
5279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005280static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005281dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005282{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005283 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005284
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005285 /* Get rid of recursion for normal control flow.
5286 Since the number of blocks is limited, unused space in a_postorder
5287 (from a_nblocks to end) can be used as a stack for still not ordered
5288 blocks. */
5289 for (j = end; b && !b->b_seen; b = b->b_next) {
5290 b->b_seen = 1;
5291 assert(a->a_nblocks < j);
5292 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005294 while (j < end) {
5295 b = a->a_postorder[j++];
5296 for (i = 0; i < b->b_iused; i++) {
5297 struct instr *instr = &b->b_instr[i];
5298 if (instr->i_jrel || instr->i_jabs)
5299 dfs(c, instr->i_target, a, j);
5300 }
5301 assert(a->a_nblocks < j);
5302 a->a_postorder[a->a_nblocks++] = b;
5303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005304}
5305
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005306Py_LOCAL_INLINE(void)
5307stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005308{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005309 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005310 if (b->b_startdepth < depth) {
5311 assert(b->b_startdepth < 0);
5312 b->b_startdepth = depth;
5313 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005315}
5316
5317/* Find the flow path that needs the largest stack. We assume that
5318 * cycles in the flow graph have no net effect on the stack depth.
5319 */
5320static int
5321stackdepth(struct compiler *c)
5322{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005323 basicblock *b, *entryblock = NULL;
5324 basicblock **stack, **sp;
5325 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 b->b_startdepth = INT_MIN;
5328 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005329 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 }
5331 if (!entryblock)
5332 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005333 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5334 if (!stack) {
5335 PyErr_NoMemory();
5336 return -1;
5337 }
5338
5339 sp = stack;
5340 stackdepth_push(&sp, entryblock, 0);
5341 while (sp != stack) {
5342 b = *--sp;
5343 int depth = b->b_startdepth;
5344 assert(depth >= 0);
5345 basicblock *next = b->b_next;
5346 for (int i = 0; i < b->b_iused; i++) {
5347 struct instr *instr = &b->b_instr[i];
5348 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5349 if (effect == PY_INVALID_STACK_EFFECT) {
5350 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5351 Py_FatalError("PyCompile_OpcodeStackEffect()");
5352 }
5353 int new_depth = depth + effect;
5354 if (new_depth > maxdepth) {
5355 maxdepth = new_depth;
5356 }
5357 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5358 if (instr->i_jrel || instr->i_jabs) {
5359 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5360 assert(effect != PY_INVALID_STACK_EFFECT);
5361 int target_depth = depth + effect;
5362 if (target_depth > maxdepth) {
5363 maxdepth = target_depth;
5364 }
5365 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005366 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005367 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005368 assert(instr->i_target->b_startdepth >= target_depth);
5369 depth = new_depth;
5370 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005371 }
5372 stackdepth_push(&sp, instr->i_target, target_depth);
5373 }
5374 depth = new_depth;
5375 if (instr->i_opcode == JUMP_ABSOLUTE ||
5376 instr->i_opcode == JUMP_FORWARD ||
5377 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005378 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005379 {
5380 /* remaining code is dead */
5381 next = NULL;
5382 break;
5383 }
5384 }
5385 if (next != NULL) {
5386 stackdepth_push(&sp, next, depth);
5387 }
5388 }
5389 PyObject_Free(stack);
5390 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005391}
5392
5393static int
5394assemble_init(struct assembler *a, int nblocks, int firstlineno)
5395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 memset(a, 0, sizeof(struct assembler));
5397 a->a_lineno = firstlineno;
5398 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5399 if (!a->a_bytecode)
5400 return 0;
5401 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5402 if (!a->a_lnotab)
5403 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005404 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 PyErr_NoMemory();
5406 return 0;
5407 }
5408 a->a_postorder = (basicblock **)PyObject_Malloc(
5409 sizeof(basicblock *) * nblocks);
5410 if (!a->a_postorder) {
5411 PyErr_NoMemory();
5412 return 0;
5413 }
5414 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005415}
5416
5417static void
5418assemble_free(struct assembler *a)
5419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 Py_XDECREF(a->a_bytecode);
5421 Py_XDECREF(a->a_lnotab);
5422 if (a->a_postorder)
5423 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005424}
5425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005426static int
5427blocksize(basicblock *b)
5428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 int i;
5430 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005433 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005435}
5436
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005437/* Appends a pair to the end of the line number table, a_lnotab, representing
5438 the instruction's bytecode offset and line number. See
5439 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005440
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005441static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005442assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005445 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447
Serhiy Storchakaab874002016-09-11 13:48:15 +03005448 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 if(d_bytecode == 0 && d_lineno == 0)
5454 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 if (d_bytecode > 255) {
5457 int j, nbytes, ncodes = d_bytecode / 255;
5458 nbytes = a->a_lnotab_off + 2 * ncodes;
5459 len = PyBytes_GET_SIZE(a->a_lnotab);
5460 if (nbytes >= len) {
5461 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5462 len = nbytes;
5463 else if (len <= INT_MAX / 2)
5464 len *= 2;
5465 else {
5466 PyErr_NoMemory();
5467 return 0;
5468 }
5469 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5470 return 0;
5471 }
5472 lnotab = (unsigned char *)
5473 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5474 for (j = 0; j < ncodes; j++) {
5475 *lnotab++ = 255;
5476 *lnotab++ = 0;
5477 }
5478 d_bytecode -= ncodes * 255;
5479 a->a_lnotab_off += ncodes * 2;
5480 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005481 assert(0 <= d_bytecode && d_bytecode <= 255);
5482
5483 if (d_lineno < -128 || 127 < d_lineno) {
5484 int j, nbytes, ncodes, k;
5485 if (d_lineno < 0) {
5486 k = -128;
5487 /* use division on positive numbers */
5488 ncodes = (-d_lineno) / 128;
5489 }
5490 else {
5491 k = 127;
5492 ncodes = d_lineno / 127;
5493 }
5494 d_lineno -= ncodes * k;
5495 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 nbytes = a->a_lnotab_off + 2 * ncodes;
5497 len = PyBytes_GET_SIZE(a->a_lnotab);
5498 if (nbytes >= len) {
5499 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5500 len = nbytes;
5501 else if (len <= INT_MAX / 2)
5502 len *= 2;
5503 else {
5504 PyErr_NoMemory();
5505 return 0;
5506 }
5507 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5508 return 0;
5509 }
5510 lnotab = (unsigned char *)
5511 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5512 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005513 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 d_bytecode = 0;
5515 for (j = 1; j < ncodes; j++) {
5516 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005517 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 a->a_lnotab_off += ncodes * 2;
5520 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005521 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 len = PyBytes_GET_SIZE(a->a_lnotab);
5524 if (a->a_lnotab_off + 2 >= len) {
5525 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5526 return 0;
5527 }
5528 lnotab = (unsigned char *)
5529 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 a->a_lnotab_off += 2;
5532 if (d_bytecode) {
5533 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005534 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 }
5536 else { /* First line of a block; def stmt, etc. */
5537 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005538 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 }
5540 a->a_lineno = i->i_lineno;
5541 a->a_lineno_off = a->a_offset;
5542 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005543}
5544
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005545/* assemble_emit()
5546 Extend the bytecode with a new instruction.
5547 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005548*/
5549
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005550static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005551assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005552{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005553 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005555 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005556
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005557 arg = i->i_oparg;
5558 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005559 if (i->i_lineno && !assemble_lnotab(a, i))
5560 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005561 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 if (len > PY_SSIZE_T_MAX / 2)
5563 return 0;
5564 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5565 return 0;
5566 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005567 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005569 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005571}
5572
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005573static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005574assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005577 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 /* Compute the size of each block and fixup jump args.
5581 Replace block pointer with position in bytecode. */
5582 do {
5583 totsize = 0;
5584 for (i = a->a_nblocks - 1; i >= 0; i--) {
5585 b = a->a_postorder[i];
5586 bsize = blocksize(b);
5587 b->b_offset = totsize;
5588 totsize += bsize;
5589 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005590 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5592 bsize = b->b_offset;
5593 for (i = 0; i < b->b_iused; i++) {
5594 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005595 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 /* Relative jumps are computed relative to
5597 the instruction pointer after fetching
5598 the jump instruction.
5599 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005600 bsize += isize;
5601 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005603 if (instr->i_jrel) {
5604 instr->i_oparg -= bsize;
5605 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005606 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005607 if (instrsize(instr->i_oparg) != isize) {
5608 extended_arg_recompile = 1;
5609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 }
5612 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 /* XXX: This is an awful hack that could hurt performance, but
5615 on the bright side it should work until we come up
5616 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 The issue is that in the first loop blocksize() is called
5619 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005620 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 So we loop until we stop seeing new EXTENDED_ARGs.
5624 The only EXTENDED_ARGs that could be popping up are
5625 ones in jump instructions. So this should converge
5626 fairly quickly.
5627 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005628 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005629}
5630
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005631static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005632dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005635 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 tuple = PyTuple_New(size);
5638 if (tuple == NULL)
5639 return NULL;
5640 while (PyDict_Next(dict, &pos, &k, &v)) {
5641 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005642 Py_INCREF(k);
5643 assert((i - offset) < size);
5644 assert((i - offset) >= 0);
5645 PyTuple_SET_ITEM(tuple, i - offset, k);
5646 }
5647 return tuple;
5648}
5649
5650static PyObject *
5651consts_dict_keys_inorder(PyObject *dict)
5652{
5653 PyObject *consts, *k, *v;
5654 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5655
5656 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5657 if (consts == NULL)
5658 return NULL;
5659 while (PyDict_Next(dict, &pos, &k, &v)) {
5660 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005661 /* The keys of the dictionary can be tuples wrapping a contant.
5662 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5663 * the object we want is always second. */
5664 if (PyTuple_CheckExact(k)) {
5665 k = PyTuple_GET_ITEM(k, 1);
5666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005668 assert(i < size);
5669 assert(i >= 0);
5670 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005672 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005673}
5674
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005675static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005679 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005681 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 if (ste->ste_nested)
5683 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005684 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005686 if (!ste->ste_generator && ste->ste_coroutine)
5687 flags |= CO_COROUTINE;
5688 if (ste->ste_generator && ste->ste_coroutine)
5689 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 if (ste->ste_varargs)
5691 flags |= CO_VARARGS;
5692 if (ste->ste_varkeywords)
5693 flags |= CO_VARKEYWORDS;
5694 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 /* (Only) inherit compilerflags in PyCF_MASK */
5697 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005700}
5701
INADA Naokic2e16072018-11-26 21:23:22 +09005702// Merge *tuple* with constant cache.
5703// Unlike merge_consts_recursive(), this function doesn't work recursively.
5704static int
5705merge_const_tuple(struct compiler *c, PyObject **tuple)
5706{
5707 assert(PyTuple_CheckExact(*tuple));
5708
5709 PyObject *key = _PyCode_ConstantKey(*tuple);
5710 if (key == NULL) {
5711 return 0;
5712 }
5713
5714 // t is borrowed reference
5715 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5716 Py_DECREF(key);
5717 if (t == NULL) {
5718 return 0;
5719 }
5720 if (t == key) { // tuple is new constant.
5721 return 1;
5722 }
5723
5724 PyObject *u = PyTuple_GET_ITEM(t, 1);
5725 Py_INCREF(u);
5726 Py_DECREF(*tuple);
5727 *tuple = u;
5728 return 1;
5729}
5730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005731static PyCodeObject *
5732makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 PyObject *tmp;
5735 PyCodeObject *co = NULL;
5736 PyObject *consts = NULL;
5737 PyObject *names = NULL;
5738 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 PyObject *name = NULL;
5740 PyObject *freevars = NULL;
5741 PyObject *cellvars = NULL;
5742 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005743 Py_ssize_t nlocals;
5744 int nlocals_int;
5745 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005746 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005747
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005748 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 names = dict_keys_inorder(c->u->u_names, 0);
5750 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5751 if (!consts || !names || !varnames)
5752 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5755 if (!cellvars)
5756 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005757 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 if (!freevars)
5759 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005760
INADA Naokic2e16072018-11-26 21:23:22 +09005761 if (!merge_const_tuple(c, &names) ||
5762 !merge_const_tuple(c, &varnames) ||
5763 !merge_const_tuple(c, &cellvars) ||
5764 !merge_const_tuple(c, &freevars))
5765 {
5766 goto error;
5767 }
5768
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005769 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005770 assert(nlocals < INT_MAX);
5771 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 flags = compute_code_flags(c);
5774 if (flags < 0)
5775 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5778 if (!bytecode)
5779 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5782 if (!tmp)
5783 goto error;
5784 Py_DECREF(consts);
5785 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005786 if (!merge_const_tuple(c, &consts)) {
5787 goto error;
5788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789
Victor Stinnerf8e32212013-11-19 23:56:34 +01005790 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5791 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005792 maxdepth = stackdepth(c);
5793 if (maxdepth < 0) {
5794 goto error;
5795 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005796 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005797 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 bytecode, consts, names, varnames,
5799 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005800 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 c->u->u_firstlineno,
5802 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005803 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 Py_XDECREF(consts);
5805 Py_XDECREF(names);
5806 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 Py_XDECREF(name);
5808 Py_XDECREF(freevars);
5809 Py_XDECREF(cellvars);
5810 Py_XDECREF(bytecode);
5811 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005812}
5813
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005814
5815/* For debugging purposes only */
5816#if 0
5817static void
5818dump_instr(const struct instr *i)
5819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 const char *jrel = i->i_jrel ? "jrel " : "";
5821 const char *jabs = i->i_jabs ? "jabs " : "";
5822 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005825 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5829 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005830}
5831
5832static void
5833dump_basicblock(const basicblock *b)
5834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 const char *seen = b->b_seen ? "seen " : "";
5836 const char *b_return = b->b_return ? "return " : "";
5837 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5838 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5839 if (b->b_instr) {
5840 int i;
5841 for (i = 0; i < b->b_iused; i++) {
5842 fprintf(stderr, " [%02d] ", i);
5843 dump_instr(b->b_instr + i);
5844 }
5845 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005846}
5847#endif
5848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005849static PyCodeObject *
5850assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 basicblock *b, *entryblock;
5853 struct assembler a;
5854 int i, j, nblocks;
5855 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 /* Make sure every block that falls off the end returns None.
5858 XXX NEXT_BLOCK() isn't quite right, because if the last
5859 block ends with a jump or return b_next shouldn't set.
5860 */
5861 if (!c->u->u_curblock->b_return) {
5862 NEXT_BLOCK(c);
5863 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005864 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 ADDOP(c, RETURN_VALUE);
5866 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 nblocks = 0;
5869 entryblock = NULL;
5870 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5871 nblocks++;
5872 entryblock = b;
5873 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 /* Set firstlineno if it wasn't explicitly set. */
5876 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005877 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5879 else
5880 c->u->u_firstlineno = 1;
5881 }
5882 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5883 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005884 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 /* Can't modify the bytecode after computing jump offsets. */
5887 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 /* Emit code in reverse postorder from dfs. */
5890 for (i = a.a_nblocks - 1; i >= 0; i--) {
5891 b = a.a_postorder[i];
5892 for (j = 0; j < b->b_iused; j++)
5893 if (!assemble_emit(&a, &b->b_instr[j]))
5894 goto error;
5895 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5898 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005899 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005903 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 assemble_free(&a);
5905 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005906}
Georg Brandl8334fd92010-12-04 10:26:46 +00005907
5908#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005909PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005910PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5911 PyArena *arena)
5912{
5913 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5914}