blob: 697833752bb0bdaa6371d12dd0b05ea0b781c5a2 [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;
Guido van Rossum495da292019-03-07 12:38:08 -0800333 local_flags.cf_feature_version = PY_MINOR_VERSION;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 flags = &local_flags;
335 }
336 merged = c.c_future->ff_features | flags->cf_flags;
337 c.c_future->ff_features = merged;
338 flags->cf_flags = merged;
339 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000340 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200343 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900344 goto finally;
345 }
346
Victor Stinner14e461d2013-08-26 22:28:21 +0200347 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (c.c_st == NULL) {
349 if (!PyErr_Occurred())
350 PyErr_SetString(PyExc_SystemError, "no symtable");
351 goto finally;
352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355
Thomas Wouters1175c432006-02-27 22:49:54 +0000356 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 compiler_free(&c);
358 assert(co || PyErr_Occurred());
359 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360}
361
362PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200363PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
364 int optimize, PyArena *arena)
365{
366 PyObject *filename;
367 PyCodeObject *co;
368 filename = PyUnicode_DecodeFSDefault(filename_str);
369 if (filename == NULL)
370 return NULL;
371 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
372 Py_DECREF(filename);
373 return co;
374
375}
376
377PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378PyNode_Compile(struct _node *n, const char *filename)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyCodeObject *co = NULL;
381 mod_ty mod;
382 PyArena *arena = PyArena_New();
383 if (!arena)
384 return NULL;
385 mod = PyAST_FromNode(n, NULL, filename, arena);
386 if (mod)
387 co = PyAST_Compile(mod, filename, NULL, arena);
388 PyArena_Free(arena);
389 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000390}
391
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (c->c_st)
396 PySymtable_Free(c->c_st);
397 if (c->c_future)
398 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200399 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900400 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402}
403
Guido van Rossum79f25d91997-04-29 20:08:16 +0000404static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ssize_t i, n;
408 PyObject *v, *k;
409 PyObject *dict = PyDict_New();
410 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 n = PyList_Size(list);
413 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100414 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (!v) {
416 Py_DECREF(dict);
417 return NULL;
418 }
419 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300420 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_DECREF(v);
422 Py_DECREF(dict);
423 return NULL;
424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_DECREF(v);
426 }
427 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428}
429
430/* Return new dict containing names from src that match scope(s).
431
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000432src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000434values are integers, starting at offset and increasing by one for
435each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436*/
437
438static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100439dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000440{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700441 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500443 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 assert(offset >= 0);
446 if (dest == NULL)
447 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448
Meador Inge2ca63152012-07-18 14:20:11 -0500449 /* Sort the keys so that we have a deterministic order on the indexes
450 saved in the returned dictionary. These indexes are used as indexes
451 into the free and cell var storage. Therefore if they aren't
452 deterministic, then the generated bytecode is not deterministic.
453 */
454 sorted_keys = PyDict_Keys(src);
455 if (sorted_keys == NULL)
456 return NULL;
457 if (PyList_Sort(sorted_keys) != 0) {
458 Py_DECREF(sorted_keys);
459 return NULL;
460 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500461 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500462
463 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* XXX this should probably be a macro in symtable.h */
465 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500466 k = PyList_GET_ITEM(sorted_keys, key_i);
467 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 assert(PyLong_Check(v));
469 vi = PyLong_AS_LONG(v);
470 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300473 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(dest);
477 return NULL;
478 }
479 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_DECREF(item);
483 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return NULL;
485 }
486 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
488 }
Meador Inge2ca63152012-07-18 14:20:11 -0500489 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000491}
492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493static void
494compiler_unit_check(struct compiler_unit *u)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 basicblock *block;
497 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700498 assert((uintptr_t)block != 0xcbcbcbcbU);
499 assert((uintptr_t)block != 0xfbfbfbfbU);
500 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (block->b_instr != NULL) {
502 assert(block->b_ialloc > 0);
503 assert(block->b_iused > 0);
504 assert(block->b_ialloc >= block->b_iused);
505 }
506 else {
507 assert (block->b_iused == 0);
508 assert (block->b_ialloc == 0);
509 }
510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511}
512
513static void
514compiler_unit_free(struct compiler_unit *u)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 compiler_unit_check(u);
519 b = u->u_blocks;
520 while (b != NULL) {
521 if (b->b_instr)
522 PyObject_Free((void *)b->b_instr);
523 next = b->b_list;
524 PyObject_Free((void *)b);
525 b = next;
526 }
527 Py_CLEAR(u->u_ste);
528 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400529 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_CLEAR(u->u_consts);
531 Py_CLEAR(u->u_names);
532 Py_CLEAR(u->u_varnames);
533 Py_CLEAR(u->u_freevars);
534 Py_CLEAR(u->u_cellvars);
535 Py_CLEAR(u->u_private);
536 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537}
538
539static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100540compiler_enter_scope(struct compiler *c, identifier name,
541 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100544 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
547 struct compiler_unit));
548 if (!u) {
549 PyErr_NoMemory();
550 return 0;
551 }
552 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100553 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 u->u_argcount = 0;
555 u->u_kwonlyargcount = 0;
556 u->u_ste = PySymtable_Lookup(c->c_st, key);
557 if (!u->u_ste) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 Py_INCREF(name);
562 u->u_name = name;
563 u->u_varnames = list2dict(u->u_ste->ste_varnames);
564 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
565 if (!u->u_varnames || !u->u_cellvars) {
566 compiler_unit_free(u);
567 return 0;
568 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000570 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300572 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 int res;
574 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200575 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500576 name = _PyUnicode_FromId(&PyId___class__);
577 if (!name) {
578 compiler_unit_free(u);
579 return 0;
580 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300581 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 if (res < 0) {
583 compiler_unit_free(u);
584 return 0;
585 }
586 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200589 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (!u->u_freevars) {
591 compiler_unit_free(u);
592 return 0;
593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_blocks = NULL;
596 u->u_nfblocks = 0;
597 u->u_firstlineno = lineno;
598 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000599 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_lineno_set = 0;
601 u->u_consts = PyDict_New();
602 if (!u->u_consts) {
603 compiler_unit_free(u);
604 return 0;
605 }
606 u->u_names = PyDict_New();
607 if (!u->u_names) {
608 compiler_unit_free(u);
609 return 0;
610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Push the old compiler_unit on the stack. */
615 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400616 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
618 Py_XDECREF(capsule);
619 compiler_unit_free(u);
620 return 0;
621 }
622 Py_DECREF(capsule);
623 u->u_private = c->u->u_private;
624 Py_XINCREF(u->u_private);
625 }
626 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100629
630 block = compiler_new_block(c);
631 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100633 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400635 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
636 if (!compiler_set_qualname(c))
637 return 0;
638 }
639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641}
642
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000643static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644compiler_exit_scope(struct compiler *c)
645{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100646 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 c->c_nestlevel--;
650 compiler_unit_free(c->u);
651 /* Restore c->u to the parent unit. */
652 n = PyList_GET_SIZE(c->c_stack) - 1;
653 if (n >= 0) {
654 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400655 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 assert(c->u);
657 /* we are deleting from a list so this really shouldn't fail */
658 if (PySequence_DelItem(c->c_stack, n) < 0)
659 Py_FatalError("compiler_exit_scope()");
660 compiler_unit_check(c->u);
661 }
662 else
663 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665}
666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667static int
668compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100670 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 _Py_static_string(dot_locals, ".<locals>");
672 Py_ssize_t stack_size;
673 struct compiler_unit *u = c->u;
674 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400678 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 if (stack_size > 1) {
680 int scope, force_global = 0;
681 struct compiler_unit *parent;
682 PyObject *mangled, *capsule;
683
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400684 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400685 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 assert(parent);
687
Yury Selivanov75445082015-05-11 22:57:16 -0400688 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
690 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 assert(u->u_name);
692 mangled = _Py_Mangle(parent->u_private, u->u_name);
693 if (!mangled)
694 return 0;
695 scope = PyST_GetScope(parent->u_ste, mangled);
696 Py_DECREF(mangled);
697 assert(scope != GLOBAL_IMPLICIT);
698 if (scope == GLOBAL_EXPLICIT)
699 force_global = 1;
700 }
701
702 if (!force_global) {
703 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400704 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
706 dot_locals_str = _PyUnicode_FromId(&dot_locals);
707 if (dot_locals_str == NULL)
708 return 0;
709 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
710 if (base == NULL)
711 return 0;
712 }
713 else {
714 Py_INCREF(parent->u_qualname);
715 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400716 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100717 }
718 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400719
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 if (base != NULL) {
721 dot_str = _PyUnicode_FromId(&dot);
722 if (dot_str == NULL) {
723 Py_DECREF(base);
724 return 0;
725 }
726 name = PyUnicode_Concat(base, dot_str);
727 Py_DECREF(base);
728 if (name == NULL)
729 return 0;
730 PyUnicode_Append(&name, u->u_name);
731 if (name == NULL)
732 return 0;
733 }
734 else {
735 Py_INCREF(u->u_name);
736 name = u->u_name;
737 }
738 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400740 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741}
742
Eric V. Smith235a6f02015-09-19 14:51:32 -0400743
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744/* Allocate a new block and return a pointer to it.
745 Returns NULL on error.
746*/
747
748static basicblock *
749compiler_new_block(struct compiler *c)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 basicblock *b;
752 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 u = c->u;
755 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
756 if (b == NULL) {
757 PyErr_NoMemory();
758 return NULL;
759 }
760 memset((void *)b, 0, sizeof(basicblock));
761 /* Extend the singly linked list of blocks with new block. */
762 b->b_list = u->u_blocks;
763 u->u_blocks = b;
764 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768compiler_next_block(struct compiler *c)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 basicblock *block = compiler_new_block(c);
771 if (block == NULL)
772 return NULL;
773 c->u->u_curblock->b_next = block;
774 c->u->u_curblock = block;
775 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
778static basicblock *
779compiler_use_next_block(struct compiler *c, basicblock *block)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 assert(block != NULL);
782 c->u->u_curblock->b_next = block;
783 c->u->u_curblock = block;
784 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785}
786
787/* Returns the offset of the next instruction in the current block's
788 b_instr array. Resizes the b_instr as necessary.
789 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000790*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791
792static int
793compiler_next_instr(struct compiler *c, basicblock *b)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(b != NULL);
796 if (b->b_instr == NULL) {
797 b->b_instr = (struct instr *)PyObject_Malloc(
798 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
799 if (b->b_instr == NULL) {
800 PyErr_NoMemory();
801 return -1;
802 }
803 b->b_ialloc = DEFAULT_BLOCK_SIZE;
804 memset((char *)b->b_instr, 0,
805 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
806 }
807 else if (b->b_iused == b->b_ialloc) {
808 struct instr *tmp;
809 size_t oldsize, newsize;
810 oldsize = b->b_ialloc * sizeof(struct instr);
811 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700813 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyErr_NoMemory();
815 return -1;
816 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (newsize == 0) {
819 PyErr_NoMemory();
820 return -1;
821 }
822 b->b_ialloc <<= 1;
823 tmp = (struct instr *)PyObject_Realloc(
824 (void *)b->b_instr, newsize);
825 if (tmp == NULL) {
826 PyErr_NoMemory();
827 return -1;
828 }
829 b->b_instr = tmp;
830 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
831 }
832 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833}
834
Christian Heimes2202f872008-02-06 14:31:34 +0000835/* Set the i_lineno member of the instruction at offset off if the
836 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 already been set. If it has been set, the call has no effect.
838
Christian Heimes2202f872008-02-06 14:31:34 +0000839 The line number is reset in the following cases:
840 - when entering a new scope
841 - on each statement
842 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200843 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000844 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847static void
848compiler_set_lineno(struct compiler *c, int off)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 basicblock *b;
851 if (c->u->u_lineno_set)
852 return;
853 c->u->u_lineno_set = 1;
854 b = c->u->u_curblock;
855 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856}
857
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200858/* Return the stack effect of opcode with argument oparg.
859
860 Some opcodes have different stack effect when jump to the target and
861 when not jump. The 'jump' parameter specifies the case:
862
863 * 0 -- when not jump
864 * 1 -- when jump
865 * -1 -- maximal
866 */
867/* XXX Make the stack effect of WITH_CLEANUP_START and
868 WITH_CLEANUP_FINISH deterministic. */
869static int
870stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300873 case NOP:
874 case EXTENDED_ARG:
875 return 0;
876
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200877 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case POP_TOP:
879 return -1;
880 case ROT_TWO:
881 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200882 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return 0;
884 case DUP_TOP:
885 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000886 case DUP_TOP_TWO:
887 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200889 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 case UNARY_POSITIVE:
891 case UNARY_NEGATIVE:
892 case UNARY_NOT:
893 case UNARY_INVERT:
894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case SET_ADD:
897 case LIST_APPEND:
898 return -1;
899 case MAP_ADD:
900 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000901
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200902 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_POWER:
904 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400905 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case BINARY_MODULO:
907 case BINARY_ADD:
908 case BINARY_SUBTRACT:
909 case BINARY_SUBSCR:
910 case BINARY_FLOOR_DIVIDE:
911 case BINARY_TRUE_DIVIDE:
912 return -1;
913 case INPLACE_FLOOR_DIVIDE:
914 case INPLACE_TRUE_DIVIDE:
915 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case INPLACE_ADD:
918 case INPLACE_SUBTRACT:
919 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400920 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case INPLACE_MODULO:
922 return -1;
923 case STORE_SUBSCR:
924 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case DELETE_SUBSCR:
926 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case BINARY_LSHIFT:
929 case BINARY_RSHIFT:
930 case BINARY_AND:
931 case BINARY_XOR:
932 case BINARY_OR:
933 return -1;
934 case INPLACE_POWER:
935 return -1;
936 case GET_ITER:
937 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case PRINT_EXPR:
940 return -1;
941 case LOAD_BUILD_CLASS:
942 return 1;
943 case INPLACE_LSHIFT:
944 case INPLACE_RSHIFT:
945 case INPLACE_AND:
946 case INPLACE_XOR:
947 case INPLACE_OR:
948 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200951 /* 1 in the normal flow.
952 * Restore the stack position and push 6 values before jumping to
953 * the handler if an exception be raised. */
954 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400955 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200956 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400957 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200958 /* Pop a variable number of values pushed by WITH_CLEANUP_START
959 * + __exit__ or __aexit__. */
960 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case RETURN_VALUE:
962 return -1;
963 case IMPORT_STAR:
964 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700965 case SETUP_ANNOTATIONS:
966 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 case YIELD_VALUE:
968 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500969 case YIELD_FROM:
970 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case POP_BLOCK:
972 return 0;
973 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200974 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200976 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200977 /* Pop 6 values when an exception was raised. */
978 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 case STORE_NAME:
981 return -1;
982 case DELETE_NAME:
983 return 0;
984 case UNPACK_SEQUENCE:
985 return oparg-1;
986 case UNPACK_EX:
987 return (oparg&0xFF) + (oparg>>8);
988 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* -1 at end of iterator, 1 if continue iterating. */
990 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case STORE_ATTR:
993 return -2;
994 case DELETE_ATTR:
995 return -1;
996 case STORE_GLOBAL:
997 return -1;
998 case DELETE_GLOBAL:
999 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case LOAD_CONST:
1001 return 1;
1002 case LOAD_NAME:
1003 return 1;
1004 case BUILD_TUPLE:
1005 case BUILD_LIST:
1006 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001007 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001009 case BUILD_LIST_UNPACK:
1010 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001011 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001012 case BUILD_SET_UNPACK:
1013 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001014 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001015 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001017 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001018 case BUILD_CONST_KEY_MAP:
1019 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_ATTR:
1021 return 0;
1022 case COMPARE_OP:
1023 return -1;
1024 case IMPORT_NAME:
1025 return -1;
1026 case IMPORT_FROM:
1027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001029 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_ABSOLUTE:
1032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001034 case JUMP_IF_TRUE_OR_POP:
1035 case JUMP_IF_FALSE_OR_POP:
1036 return jump ? 0 : -1;
1037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case POP_JUMP_IF_FALSE:
1039 case POP_JUMP_IF_TRUE:
1040 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_GLOBAL:
1043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001045 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001047 /* 0 in the normal flow.
1048 * Restore the stack position and push 6 values before jumping to
1049 * the handler if an exception be raised. */
1050 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001051 case BEGIN_FINALLY:
1052 /* Actually pushes 1 value, but count 6 for balancing with
1053 * END_FINALLY and POP_FINALLY.
1054 * This is the main reason of using this opcode instead of
1055 * "LOAD_CONST None". */
1056 return 6;
1057 case CALL_FINALLY:
1058 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_FAST:
1061 return 1;
1062 case STORE_FAST:
1063 return -1;
1064 case DELETE_FAST:
1065 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case RAISE_VARARGS:
1068 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001069
1070 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001072 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001073 case CALL_METHOD:
1074 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001076 return -oparg-1;
1077 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001078 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001079 case MAKE_FUNCTION:
1080 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1081 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case BUILD_SLICE:
1083 if (oparg == 3)
1084 return -2;
1085 else
1086 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case LOAD_CLOSURE:
1090 return 1;
1091 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001092 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 return 1;
1094 case STORE_DEREF:
1095 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001096 case DELETE_DEREF:
1097 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098
1099 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001100 case GET_AWAITABLE:
1101 return 0;
1102 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 /* 0 in the normal flow.
1104 * Restore the stack position to the position before the result
1105 * of __aenter__ and push 6 values before jumping to the handler
1106 * if an exception be raised. */
1107 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case BEFORE_ASYNC_WITH:
1109 return 1;
1110 case GET_AITER:
1111 return 0;
1112 case GET_ANEXT:
1113 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001114 case GET_YIELD_FROM_ITER:
1115 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001116 case END_ASYNC_FOR:
1117 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001118 case FORMAT_VALUE:
1119 /* If there's a fmt_spec on the stack, we go from 2->1,
1120 else 1->1. */
1121 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001122 case LOAD_METHOD:
1123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001125 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
Larry Hastings3a907972013-11-23 14:49:22 -08001127 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128}
1129
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001130int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001131PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1132{
1133 return stack_effect(opcode, oparg, jump);
1134}
1135
1136int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001137PyCompile_OpcodeStackEffect(int opcode, int oparg)
1138{
1139 return stack_effect(opcode, oparg, -1);
1140}
1141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142/* Add an opcode with no argument.
1143 Returns 0 on failure, 1 on success.
1144*/
1145
1146static int
1147compiler_addop(struct compiler *c, int opcode)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 basicblock *b;
1150 struct instr *i;
1151 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001152 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 off = compiler_next_instr(c, c->u->u_curblock);
1154 if (off < 0)
1155 return 0;
1156 b = c->u->u_curblock;
1157 i = &b->b_instr[off];
1158 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001159 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (opcode == RETURN_VALUE)
1161 b->b_return = 1;
1162 compiler_set_lineno(c, off);
1163 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Victor Stinnerf8e32212013-11-19 23:56:34 +01001166static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1168{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001169 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001174 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001176 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001177 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001178 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return -1;
1181 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
1184 return -1;
1185 }
1186 Py_DECREF(v);
1187 }
1188 else
1189 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001190 return arg;
1191}
1192
INADA Naokic2e16072018-11-26 21:23:22 +09001193// Merge const *o* recursively and return constant key object.
1194static PyObject*
1195merge_consts_recursive(struct compiler *c, PyObject *o)
1196{
1197 // None and Ellipsis are singleton, and key is the singleton.
1198 // No need to merge object and key.
1199 if (o == Py_None || o == Py_Ellipsis) {
1200 Py_INCREF(o);
1201 return o;
1202 }
1203
1204 PyObject *key = _PyCode_ConstantKey(o);
1205 if (key == NULL) {
1206 return NULL;
1207 }
1208
1209 // t is borrowed reference
1210 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1211 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001212 // o is registered in c_const_cache. Just use it.
INADA Naokic2e16072018-11-26 21:23:22 +09001213 Py_INCREF(t);
1214 Py_DECREF(key);
1215 return t;
1216 }
1217
INADA Naokif7e4d362018-11-29 00:58:46 +09001218 // We registered o in c_const_cache.
1219 // When o is a tuple or frozenset, we want to merge it's
1220 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001221 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 Py_ssize_t len = PyTuple_GET_SIZE(o);
1223 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001224 PyObject *item = PyTuple_GET_ITEM(o, i);
1225 PyObject *u = merge_consts_recursive(c, item);
1226 if (u == NULL) {
1227 Py_DECREF(key);
1228 return NULL;
1229 }
1230
1231 // See _PyCode_ConstantKey()
1232 PyObject *v; // borrowed
1233 if (PyTuple_CheckExact(u)) {
1234 v = PyTuple_GET_ITEM(u, 1);
1235 }
1236 else {
1237 v = u;
1238 }
1239 if (v != item) {
1240 Py_INCREF(v);
1241 PyTuple_SET_ITEM(o, i, v);
1242 Py_DECREF(item);
1243 }
1244
1245 Py_DECREF(u);
1246 }
1247 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001248 else if (PyFrozenSet_CheckExact(o)) {
1249 // *key* is tuple. And it's first item is frozenset of
1250 // constant keys.
1251 // See _PyCode_ConstantKey() for detail.
1252 assert(PyTuple_CheckExact(key));
1253 assert(PyTuple_GET_SIZE(key) == 2);
1254
1255 Py_ssize_t len = PySet_GET_SIZE(o);
1256 if (len == 0) { // empty frozenset should not be re-created.
1257 return key;
1258 }
1259 PyObject *tuple = PyTuple_New(len);
1260 if (tuple == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264 Py_ssize_t i = 0, pos = 0;
1265 PyObject *item;
1266 Py_hash_t hash;
1267 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1268 PyObject *k = merge_consts_recursive(c, item);
1269 if (k == NULL) {
1270 Py_DECREF(tuple);
1271 Py_DECREF(key);
1272 return NULL;
1273 }
1274 PyObject *u;
1275 if (PyTuple_CheckExact(k)) {
1276 u = PyTuple_GET_ITEM(k, 1);
1277 Py_INCREF(u);
1278 Py_DECREF(k);
1279 }
1280 else {
1281 u = k;
1282 }
1283 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1284 i++;
1285 }
1286
1287 // Instead of rewriting o, we create new frozenset and embed in the
1288 // key tuple. Caller should get merged frozenset from the key tuple.
1289 PyObject *new = PyFrozenSet_New(tuple);
1290 Py_DECREF(tuple);
1291 if (new == NULL) {
1292 Py_DECREF(key);
1293 return NULL;
1294 }
1295 assert(PyTuple_GET_ITEM(key, 1) == o);
1296 Py_DECREF(o);
1297 PyTuple_SET_ITEM(key, 1, new);
1298 }
INADA Naokic2e16072018-11-26 21:23:22 +09001299
1300 return key;
1301}
1302
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001303static Py_ssize_t
1304compiler_add_const(struct compiler *c, PyObject *o)
1305{
INADA Naokic2e16072018-11-26 21:23:22 +09001306 PyObject *key = merge_consts_recursive(c, o);
1307 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001308 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001309 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310
INADA Naokic2e16072018-11-26 21:23:22 +09001311 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1312 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314}
1315
1316static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001317compiler_addop_load_const(struct compiler *c, PyObject *o)
1318{
1319 Py_ssize_t arg = compiler_add_const(c, o);
1320 if (arg < 0)
1321 return 0;
1322 return compiler_addop_i(c, LOAD_CONST, arg);
1323}
1324
1325static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001329 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001331 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 return compiler_addop_i(c, opcode, arg);
1333}
1334
1335static int
1336compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001339 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1341 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001342 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343 arg = compiler_add_o(c, dict, mangled);
1344 Py_DECREF(mangled);
1345 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return compiler_addop_i(c, opcode, arg);
1348}
1349
1350/* Add an opcode with an integer argument.
1351 Returns 0 on failure, 1 on success.
1352*/
1353
1354static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001355compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 struct instr *i;
1358 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001359
Victor Stinner2ad474b2016-03-01 23:34:47 +01001360 /* oparg value is unsigned, but a signed C int is usually used to store
1361 it in the C code (like Python/ceval.c).
1362
1363 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1364
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001365 The argument of a concrete bytecode instruction is limited to 8-bit.
1366 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1367 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001368 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 off = compiler_next_instr(c, c->u->u_curblock);
1371 if (off < 0)
1372 return 0;
1373 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001374 i->i_opcode = opcode;
1375 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 compiler_set_lineno(c, off);
1377 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378}
1379
1380static int
1381compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 struct instr *i;
1384 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001386 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 assert(b != NULL);
1388 off = compiler_next_instr(c, c->u->u_curblock);
1389 if (off < 0)
1390 return 0;
1391 i = &c->u->u_curblock->b_instr[off];
1392 i->i_opcode = opcode;
1393 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (absolute)
1395 i->i_jabs = 1;
1396 else
1397 i->i_jrel = 1;
1398 compiler_set_lineno(c, off);
1399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400}
1401
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001402/* NEXT_BLOCK() creates an implicit jump from the current block
1403 to the new block.
1404
1405 The returns inside this macro make it impossible to decref objects
1406 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (compiler_next_block((C)) == NULL) \
1410 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411}
1412
1413#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (!compiler_addop((C), (OP))) \
1415 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416}
1417
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001418#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (!compiler_addop((C), (OP))) { \
1420 compiler_exit_scope(c); \
1421 return 0; \
1422 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001423}
1424
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001425#define ADDOP_LOAD_CONST(C, O) { \
1426 if (!compiler_addop_load_const((C), (O))) \
1427 return 0; \
1428}
1429
1430/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1431#define ADDOP_LOAD_CONST_NEW(C, O) { \
1432 PyObject *__new_const = (O); \
1433 if (__new_const == NULL) { \
1434 return 0; \
1435 } \
1436 if (!compiler_addop_load_const((C), __new_const)) { \
1437 Py_DECREF(__new_const); \
1438 return 0; \
1439 } \
1440 Py_DECREF(__new_const); \
1441}
1442
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1445 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446}
1447
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001448/* Same as ADDOP_O, but steals a reference. */
1449#define ADDOP_N(C, OP, O, TYPE) { \
1450 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1451 Py_DECREF((O)); \
1452 return 0; \
1453 } \
1454 Py_DECREF((O)); \
1455}
1456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1459 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460}
1461
1462#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (!compiler_addop_i((C), (OP), (O))) \
1464 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465}
1466
1467#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (!compiler_addop_j((C), (OP), (O), 1)) \
1469 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470}
1471
1472#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!compiler_addop_j((C), (OP), (O), 0)) \
1474 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475}
1476
1477/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1478 the ASDL name to synthesize the name of the C type and the visit function.
1479*/
1480
1481#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_visit_ ## TYPE((C), (V))) \
1483 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484}
1485
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001486#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (!compiler_visit_ ## TYPE((C), (V))) { \
1488 compiler_exit_scope(c); \
1489 return 0; \
1490 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001491}
1492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!compiler_visit_slice((C), (V), (CTX))) \
1495 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int _i; \
1500 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1501 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1502 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1503 if (!compiler_visit_ ## TYPE((C), elt)) \
1504 return 0; \
1505 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506}
1507
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001508#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 int _i; \
1510 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1511 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1512 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1513 if (!compiler_visit_ ## TYPE((C), elt)) { \
1514 compiler_exit_scope(c); \
1515 return 0; \
1516 } \
1517 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001518}
1519
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001520/* Search if variable annotations are present statically in a block. */
1521
1522static int
1523find_ann(asdl_seq *stmts)
1524{
1525 int i, j, res = 0;
1526 stmt_ty st;
1527
1528 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1529 st = (stmt_ty)asdl_seq_GET(stmts, i);
1530 switch (st->kind) {
1531 case AnnAssign_kind:
1532 return 1;
1533 case For_kind:
1534 res = find_ann(st->v.For.body) ||
1535 find_ann(st->v.For.orelse);
1536 break;
1537 case AsyncFor_kind:
1538 res = find_ann(st->v.AsyncFor.body) ||
1539 find_ann(st->v.AsyncFor.orelse);
1540 break;
1541 case While_kind:
1542 res = find_ann(st->v.While.body) ||
1543 find_ann(st->v.While.orelse);
1544 break;
1545 case If_kind:
1546 res = find_ann(st->v.If.body) ||
1547 find_ann(st->v.If.orelse);
1548 break;
1549 case With_kind:
1550 res = find_ann(st->v.With.body);
1551 break;
1552 case AsyncWith_kind:
1553 res = find_ann(st->v.AsyncWith.body);
1554 break;
1555 case Try_kind:
1556 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1557 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1558 st->v.Try.handlers, j);
1559 if (find_ann(handler->v.ExceptHandler.body)) {
1560 return 1;
1561 }
1562 }
1563 res = find_ann(st->v.Try.body) ||
1564 find_ann(st->v.Try.finalbody) ||
1565 find_ann(st->v.Try.orelse);
1566 break;
1567 default:
1568 res = 0;
1569 }
1570 if (res) {
1571 break;
1572 }
1573 }
1574 return res;
1575}
1576
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001577/*
1578 * Frame block handling functions
1579 */
1580
1581static int
1582compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1583 basicblock *exit)
1584{
1585 struct fblockinfo *f;
1586 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1587 PyErr_SetString(PyExc_SyntaxError,
1588 "too many statically nested blocks");
1589 return 0;
1590 }
1591 f = &c->u->u_fblock[c->u->u_nfblocks++];
1592 f->fb_type = t;
1593 f->fb_block = b;
1594 f->fb_exit = exit;
1595 return 1;
1596}
1597
1598static void
1599compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1600{
1601 struct compiler_unit *u = c->u;
1602 assert(u->u_nfblocks > 0);
1603 u->u_nfblocks--;
1604 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1605 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1606}
1607
1608/* Unwind a frame block. If preserve_tos is true, the TOS before
1609 * popping the blocks will be restored afterwards.
1610 */
1611static int
1612compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1613 int preserve_tos)
1614{
1615 switch (info->fb_type) {
1616 case WHILE_LOOP:
1617 return 1;
1618
1619 case FINALLY_END:
1620 ADDOP_I(c, POP_FINALLY, preserve_tos);
1621 return 1;
1622
1623 case FOR_LOOP:
1624 /* Pop the iterator */
1625 if (preserve_tos) {
1626 ADDOP(c, ROT_TWO);
1627 }
1628 ADDOP(c, POP_TOP);
1629 return 1;
1630
1631 case EXCEPT:
1632 ADDOP(c, POP_BLOCK);
1633 return 1;
1634
1635 case FINALLY_TRY:
1636 ADDOP(c, POP_BLOCK);
1637 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1638 return 1;
1639
1640 case WITH:
1641 case ASYNC_WITH:
1642 ADDOP(c, POP_BLOCK);
1643 if (preserve_tos) {
1644 ADDOP(c, ROT_TWO);
1645 }
1646 ADDOP(c, BEGIN_FINALLY);
1647 ADDOP(c, WITH_CLEANUP_START);
1648 if (info->fb_type == ASYNC_WITH) {
1649 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001650 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001651 ADDOP(c, YIELD_FROM);
1652 }
1653 ADDOP(c, WITH_CLEANUP_FINISH);
1654 ADDOP_I(c, POP_FINALLY, 0);
1655 return 1;
1656
1657 case HANDLER_CLEANUP:
1658 if (preserve_tos) {
1659 ADDOP(c, ROT_FOUR);
1660 }
1661 if (info->fb_exit) {
1662 ADDOP(c, POP_BLOCK);
1663 ADDOP(c, POP_EXCEPT);
1664 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1665 }
1666 else {
1667 ADDOP(c, POP_EXCEPT);
1668 }
1669 return 1;
1670 }
1671 Py_UNREACHABLE();
1672}
1673
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001674/* Compile a sequence of statements, checking for a docstring
1675 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
1677static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001678compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001680 int i = 0;
1681 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001682 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001683
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001684 /* Set current line number to the line number of first statement.
1685 This way line number for SETUP_ANNOTATIONS will always
1686 coincide with the line number of first "real" statement in module.
1687 If body is empy, then lineno will be set later in assemble. */
1688 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1689 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001690 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001691 c->u->u_lineno = st->lineno;
1692 }
1693 /* Every annotated class and module should have __annotations__. */
1694 if (find_ann(stmts)) {
1695 ADDOP(c, SETUP_ANNOTATIONS);
1696 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001697 if (!asdl_seq_LEN(stmts))
1698 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001699 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001700 if (c->c_optimize < 2) {
1701 docstring = _PyAST_GetDocString(stmts);
1702 if (docstring) {
1703 i = 1;
1704 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1705 assert(st->kind == Expr_kind);
1706 VISIT(c, expr, st->v.Expr.value);
1707 if (!compiler_nameop(c, __doc__, Store))
1708 return 0;
1709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001711 for (; i < asdl_seq_LEN(stmts); i++)
1712 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714}
1715
1716static PyCodeObject *
1717compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyCodeObject *co;
1720 int addNone = 1;
1721 static PyObject *module;
1722 if (!module) {
1723 module = PyUnicode_InternFromString("<module>");
1724 if (!module)
1725 return NULL;
1726 }
1727 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001728 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return NULL;
1730 switch (mod->kind) {
1731 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001732 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 compiler_exit_scope(c);
1734 return 0;
1735 }
1736 break;
1737 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001738 if (find_ann(mod->v.Interactive.body)) {
1739 ADDOP(c, SETUP_ANNOTATIONS);
1740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 c->c_interactive = 1;
1742 VISIT_SEQ_IN_SCOPE(c, stmt,
1743 mod->v.Interactive.body);
1744 break;
1745 case Expression_kind:
1746 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1747 addNone = 0;
1748 break;
1749 case Suite_kind:
1750 PyErr_SetString(PyExc_SystemError,
1751 "suite should not be possible");
1752 return 0;
1753 default:
1754 PyErr_Format(PyExc_SystemError,
1755 "module kind %d should not be possible",
1756 mod->kind);
1757 return 0;
1758 }
1759 co = assemble(c, addNone);
1760 compiler_exit_scope(c);
1761 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001762}
1763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764/* The test for LOCAL must come before the test for FREE in order to
1765 handle classes where name is both local and free. The local var is
1766 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001767*/
1768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769static int
1770get_ref_type(struct compiler *c, PyObject *name)
1771{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001772 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001773 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001774 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001775 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001776 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (scope == 0) {
1778 char buf[350];
1779 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001780 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001782 PyUnicode_AsUTF8(name),
1783 PyUnicode_AsUTF8(c->u->u_name),
1784 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1785 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1787 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 );
1789 Py_FatalError(buf);
1790 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793}
1794
1795static int
1796compiler_lookup_arg(PyObject *dict, PyObject *name)
1797{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001798 PyObject *v;
1799 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001801 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001802 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803}
1804
1805static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001806compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001808 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001809 if (qualname == NULL)
1810 qualname = co->co_name;
1811
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001812 if (free) {
1813 for (i = 0; i < free; ++i) {
1814 /* Bypass com_addop_varname because it will generate
1815 LOAD_DEREF but LOAD_CLOSURE is needed.
1816 */
1817 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1818 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001820 /* Special case: If a class contains a method with a
1821 free variable that has the same name as a method,
1822 the name will be considered free *and* local in the
1823 class. It should be handled by the closure, as
1824 well as by the normal name loookup logic.
1825 */
1826 reftype = get_ref_type(c, name);
1827 if (reftype == CELL)
1828 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1829 else /* (reftype == FREE) */
1830 arg = compiler_lookup_arg(c->u->u_freevars, name);
1831 if (arg == -1) {
1832 fprintf(stderr,
1833 "lookup %s in %s %d %d\n"
1834 "freevars of %s: %s\n",
1835 PyUnicode_AsUTF8(PyObject_Repr(name)),
1836 PyUnicode_AsUTF8(c->u->u_name),
1837 reftype, arg,
1838 PyUnicode_AsUTF8(co->co_name),
1839 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1840 Py_FatalError("compiler_make_closure()");
1841 }
1842 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001844 flags |= 0x08;
1845 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001847 ADDOP_LOAD_CONST(c, (PyObject*)co);
1848 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001849 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853static int
1854compiler_decorators(struct compiler *c, asdl_seq* decos)
1855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (!decos)
1859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1862 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1863 }
1864 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865}
1866
1867static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001868compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001870{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001871 /* Push a dict of keyword-only default values.
1872
1873 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1874 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001875 int i;
1876 PyObject *keys = NULL;
1877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1879 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1880 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1881 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001882 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001883 if (!mangled) {
1884 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001886 if (keys == NULL) {
1887 keys = PyList_New(1);
1888 if (keys == NULL) {
1889 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001890 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001891 }
1892 PyList_SET_ITEM(keys, 0, mangled);
1893 }
1894 else {
1895 int res = PyList_Append(keys, mangled);
1896 Py_DECREF(mangled);
1897 if (res == -1) {
1898 goto error;
1899 }
1900 }
1901 if (!compiler_visit_expr(c, default_)) {
1902 goto error;
1903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 }
1905 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906 if (keys != NULL) {
1907 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1908 PyObject *keys_tuple = PyList_AsTuple(keys);
1909 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001910 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001912 assert(default_count > 0);
1913 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001914 }
1915 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001916 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001917 }
1918
1919error:
1920 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001921 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001922}
1923
1924static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001925compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1926{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001927 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001928 return 1;
1929}
1930
1931static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001932compiler_visit_argannotation(struct compiler *c, identifier id,
1933 expr_ty annotation, PyObject *names)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001936 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001937 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1938 VISIT(c, annexpr, annotation)
1939 }
1940 else {
1941 VISIT(c, expr, annotation);
1942 }
Victor Stinner065efc32014-02-18 22:07:56 +01001943 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001944 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001945 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001946 if (PyList_Append(names, mangled) < 0) {
1947 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001948 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001949 }
1950 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001952 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001953}
1954
1955static int
1956compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1957 PyObject *names)
1958{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001959 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 for (i = 0; i < asdl_seq_LEN(args); i++) {
1961 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001962 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 c,
1964 arg->arg,
1965 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001966 names))
1967 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001969 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001970}
1971
1972static int
1973compiler_visit_annotations(struct compiler *c, arguments_ty args,
1974 expr_ty returns)
1975{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001976 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001977 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001978
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001979 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 */
1981 static identifier return_str;
1982 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001983 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 names = PyList_New(0);
1985 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001986 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001987
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001988 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001990 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001991 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001992 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001994 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001996 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001997 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001998 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (!return_str) {
2002 return_str = PyUnicode_InternFromString("return");
2003 if (!return_str)
2004 goto error;
2005 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002006 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 goto error;
2008 }
2009
2010 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 PyObject *keytuple = PyList_AsTuple(names);
2013 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002014 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002016 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 else {
2019 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002020 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002022
2023error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002025 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002026}
2027
2028static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002029compiler_visit_defaults(struct compiler *c, arguments_ty args)
2030{
2031 VISIT_SEQ(c, expr, args->defaults);
2032 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002036static Py_ssize_t
2037compiler_default_arguments(struct compiler *c, arguments_ty args)
2038{
2039 Py_ssize_t funcflags = 0;
2040 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002041 if (!compiler_visit_defaults(c, args))
2042 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002043 funcflags |= 0x01;
2044 }
2045 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002046 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002047 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002048 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 return -1;
2050 }
2051 else if (res > 0) {
2052 funcflags |= 0x02;
2053 }
2054 }
2055 return funcflags;
2056}
2057
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058static int
Yury Selivanov75445082015-05-11 22:57:16 -04002059compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002062 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002063 arguments_ty args;
2064 expr_ty returns;
2065 identifier name;
2066 asdl_seq* decos;
2067 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002068 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002069 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002070 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002071 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Yury Selivanov75445082015-05-11 22:57:16 -04002073 if (is_async) {
2074 assert(s->kind == AsyncFunctionDef_kind);
2075
2076 args = s->v.AsyncFunctionDef.args;
2077 returns = s->v.AsyncFunctionDef.returns;
2078 decos = s->v.AsyncFunctionDef.decorator_list;
2079 name = s->v.AsyncFunctionDef.name;
2080 body = s->v.AsyncFunctionDef.body;
2081
2082 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2083 } else {
2084 assert(s->kind == FunctionDef_kind);
2085
2086 args = s->v.FunctionDef.args;
2087 returns = s->v.FunctionDef.returns;
2088 decos = s->v.FunctionDef.decorator_list;
2089 name = s->v.FunctionDef.name;
2090 body = s->v.FunctionDef.body;
2091
2092 scope_type = COMPILER_SCOPE_FUNCTION;
2093 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (!compiler_decorators(c, decos))
2096 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002097
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002098 firstlineno = s->lineno;
2099 if (asdl_seq_LEN(decos)) {
2100 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2101 }
2102
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002103 funcflags = compiler_default_arguments(c, args);
2104 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002106 }
2107
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002108 annotations = compiler_visit_annotations(c, args, returns);
2109 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002110 return 0;
2111 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002112 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002113 funcflags |= 0x04;
2114 }
2115
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002116 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002117 return 0;
2118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119
INADA Naokicb41b272017-02-23 00:31:59 +09002120 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002121 if (c->c_optimize < 2) {
2122 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002123 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002124 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 compiler_exit_scope(c);
2126 return 0;
2127 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 c->u->u_argcount = asdl_seq_LEN(args->args);
2130 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002131 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002133 qualname = c->u->u_qualname;
2134 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002136 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002137 Py_XDECREF(qualname);
2138 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002142 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002143 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* decorators */
2147 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2148 ADDOP_I(c, CALL_FUNCTION, 1);
2149 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150
Yury Selivanov75445082015-05-11 22:57:16 -04002151 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152}
2153
2154static int
2155compiler_class(struct compiler *c, stmt_ty s)
2156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyCodeObject *co;
2158 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002159 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (!compiler_decorators(c, decos))
2163 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002164
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002165 firstlineno = s->lineno;
2166 if (asdl_seq_LEN(decos)) {
2167 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2168 }
2169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* ultimately generate code for:
2171 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2172 where:
2173 <func> is a function/closure created from the class body;
2174 it has a single argument (__locals__) where the dict
2175 (or MutableSequence) representing the locals is passed
2176 <name> is the class name
2177 <bases> is the positional arguments and *varargs argument
2178 <keywords> is the keyword arguments and **kwds argument
2179 This borrows from compiler_call.
2180 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002183 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002184 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 return 0;
2186 /* this block represents what we do in the new scope */
2187 {
2188 /* use the class name for name mangling */
2189 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002190 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* load (global) __name__ ... */
2192 str = PyUnicode_InternFromString("__name__");
2193 if (!str || !compiler_nameop(c, str, Load)) {
2194 Py_XDECREF(str);
2195 compiler_exit_scope(c);
2196 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 Py_DECREF(str);
2199 /* ... and store it as __module__ */
2200 str = PyUnicode_InternFromString("__module__");
2201 if (!str || !compiler_nameop(c, str, Store)) {
2202 Py_XDECREF(str);
2203 compiler_exit_scope(c);
2204 return 0;
2205 }
2206 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002207 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002208 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002209 str = PyUnicode_InternFromString("__qualname__");
2210 if (!str || !compiler_nameop(c, str, Store)) {
2211 Py_XDECREF(str);
2212 compiler_exit_scope(c);
2213 return 0;
2214 }
2215 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002217 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 compiler_exit_scope(c);
2219 return 0;
2220 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002221 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002222 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002223 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002224 str = PyUnicode_InternFromString("__class__");
2225 if (str == NULL) {
2226 compiler_exit_scope(c);
2227 return 0;
2228 }
2229 i = compiler_lookup_arg(c->u->u_cellvars, str);
2230 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002231 if (i < 0) {
2232 compiler_exit_scope(c);
2233 return 0;
2234 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002235 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002238 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002239 str = PyUnicode_InternFromString("__classcell__");
2240 if (!str || !compiler_nameop(c, str, Store)) {
2241 Py_XDECREF(str);
2242 compiler_exit_scope(c);
2243 return 0;
2244 }
2245 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002247 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002248 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002249 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002250 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002251 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002252 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* create the code object */
2254 co = assemble(c, 1);
2255 }
2256 /* leave the new scope */
2257 compiler_exit_scope(c);
2258 if (co == NULL)
2259 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* 2. load the 'build_class' function */
2262 ADDOP(c, LOAD_BUILD_CLASS);
2263
2264 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002265 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 Py_DECREF(co);
2267
2268 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002269 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270
2271 /* 5. generate the rest of the code for the call */
2272 if (!compiler_call_helper(c, 2,
2273 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002274 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 return 0;
2276
2277 /* 6. apply decorators */
2278 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2279 ADDOP_I(c, CALL_FUNCTION, 1);
2280 }
2281
2282 /* 7. store into <name> */
2283 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2284 return 0;
2285 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286}
2287
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002288/* Return 0 if the expression is a constant value except named singletons.
2289 Return 1 otherwise. */
2290static int
2291check_is_arg(expr_ty e)
2292{
2293 if (e->kind != Constant_kind) {
2294 return 1;
2295 }
2296 PyObject *value = e->v.Constant.value;
2297 return (value == Py_None
2298 || value == Py_False
2299 || value == Py_True
2300 || value == Py_Ellipsis);
2301}
2302
2303/* Check operands of identity chacks ("is" and "is not").
2304 Emit a warning if any operand is a constant except named singletons.
2305 Return 0 on error.
2306 */
2307static int
2308check_compare(struct compiler *c, expr_ty e)
2309{
2310 Py_ssize_t i, n;
2311 int left = check_is_arg(e->v.Compare.left);
2312 n = asdl_seq_LEN(e->v.Compare.ops);
2313 for (i = 0; i < n; i++) {
2314 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2315 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2316 if (op == Is || op == IsNot) {
2317 if (!right || !left) {
2318 const char *msg = (op == Is)
2319 ? "\"is\" with a literal. Did you mean \"==\"?"
2320 : "\"is not\" with a literal. Did you mean \"!=\"?";
2321 return compiler_warn(c, msg);
2322 }
2323 }
2324 left = right;
2325 }
2326 return 1;
2327}
2328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002330cmpop(cmpop_ty op)
2331{
2332 switch (op) {
2333 case Eq:
2334 return PyCmp_EQ;
2335 case NotEq:
2336 return PyCmp_NE;
2337 case Lt:
2338 return PyCmp_LT;
2339 case LtE:
2340 return PyCmp_LE;
2341 case Gt:
2342 return PyCmp_GT;
2343 case GtE:
2344 return PyCmp_GE;
2345 case Is:
2346 return PyCmp_IS;
2347 case IsNot:
2348 return PyCmp_IS_NOT;
2349 case In:
2350 return PyCmp_IN;
2351 case NotIn:
2352 return PyCmp_NOT_IN;
2353 default:
2354 return PyCmp_BAD;
2355 }
2356}
2357
2358static int
2359compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2360{
2361 switch (e->kind) {
2362 case UnaryOp_kind:
2363 if (e->v.UnaryOp.op == Not)
2364 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2365 /* fallback to general implementation */
2366 break;
2367 case BoolOp_kind: {
2368 asdl_seq *s = e->v.BoolOp.values;
2369 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2370 assert(n >= 0);
2371 int cond2 = e->v.BoolOp.op == Or;
2372 basicblock *next2 = next;
2373 if (!cond2 != !cond) {
2374 next2 = compiler_new_block(c);
2375 if (next2 == NULL)
2376 return 0;
2377 }
2378 for (i = 0; i < n; ++i) {
2379 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2380 return 0;
2381 }
2382 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2383 return 0;
2384 if (next2 != next)
2385 compiler_use_next_block(c, next2);
2386 return 1;
2387 }
2388 case IfExp_kind: {
2389 basicblock *end, *next2;
2390 end = compiler_new_block(c);
2391 if (end == NULL)
2392 return 0;
2393 next2 = compiler_new_block(c);
2394 if (next2 == NULL)
2395 return 0;
2396 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2397 return 0;
2398 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2399 return 0;
2400 ADDOP_JREL(c, JUMP_FORWARD, end);
2401 compiler_use_next_block(c, next2);
2402 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2403 return 0;
2404 compiler_use_next_block(c, end);
2405 return 1;
2406 }
2407 case Compare_kind: {
2408 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2409 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002410 if (!check_compare(c, e)) {
2411 return 0;
2412 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002413 basicblock *cleanup = compiler_new_block(c);
2414 if (cleanup == NULL)
2415 return 0;
2416 VISIT(c, expr, e->v.Compare.left);
2417 for (i = 0; i < n; i++) {
2418 VISIT(c, expr,
2419 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2420 ADDOP(c, DUP_TOP);
2421 ADDOP(c, ROT_THREE);
2422 ADDOP_I(c, COMPARE_OP,
2423 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2424 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2425 NEXT_BLOCK(c);
2426 }
2427 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2428 ADDOP_I(c, COMPARE_OP,
2429 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2430 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2431 basicblock *end = compiler_new_block(c);
2432 if (end == NULL)
2433 return 0;
2434 ADDOP_JREL(c, JUMP_FORWARD, end);
2435 compiler_use_next_block(c, cleanup);
2436 ADDOP(c, POP_TOP);
2437 if (!cond) {
2438 ADDOP_JREL(c, JUMP_FORWARD, next);
2439 }
2440 compiler_use_next_block(c, end);
2441 return 1;
2442 }
2443 /* fallback to general implementation */
2444 break;
2445 }
2446 default:
2447 /* fallback to general implementation */
2448 break;
2449 }
2450
2451 /* general implementation */
2452 VISIT(c, expr, e);
2453 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2454 return 1;
2455}
2456
2457static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002458compiler_ifexp(struct compiler *c, expr_ty e)
2459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 basicblock *end, *next;
2461
2462 assert(e->kind == IfExp_kind);
2463 end = compiler_new_block(c);
2464 if (end == NULL)
2465 return 0;
2466 next = compiler_new_block(c);
2467 if (next == NULL)
2468 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2470 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 VISIT(c, expr, e->v.IfExp.body);
2472 ADDOP_JREL(c, JUMP_FORWARD, end);
2473 compiler_use_next_block(c, next);
2474 VISIT(c, expr, e->v.IfExp.orelse);
2475 compiler_use_next_block(c, end);
2476 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002477}
2478
2479static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480compiler_lambda(struct compiler *c, expr_ty e)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002483 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002485 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 arguments_ty args = e->v.Lambda.args;
2487 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (!name) {
2490 name = PyUnicode_InternFromString("<lambda>");
2491 if (!name)
2492 return 0;
2493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002495 funcflags = compiler_default_arguments(c, args);
2496 if (funcflags == -1) {
2497 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002499
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002500 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002501 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* Make None the first constant, so the lambda can't have a
2505 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002506 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 c->u->u_argcount = asdl_seq_LEN(args->args);
2510 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2511 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2512 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002513 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 }
2515 else {
2516 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002517 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002519 qualname = c->u->u_qualname;
2520 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002522 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002525 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002526 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 Py_DECREF(co);
2528
2529 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530}
2531
2532static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533compiler_if(struct compiler *c, stmt_ty s)
2534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 basicblock *end, *next;
2536 int constant;
2537 assert(s->kind == If_kind);
2538 end = compiler_new_block(c);
2539 if (end == NULL)
2540 return 0;
2541
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002542 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* constant = 0: "if 0"
2544 * constant = 1: "if 1", "if 2", ...
2545 * constant = -1: rest */
2546 if (constant == 0) {
2547 if (s->v.If.orelse)
2548 VISIT_SEQ(c, stmt, s->v.If.orelse);
2549 } else if (constant == 1) {
2550 VISIT_SEQ(c, stmt, s->v.If.body);
2551 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002552 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 next = compiler_new_block(c);
2554 if (next == NULL)
2555 return 0;
2556 }
2557 else
2558 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002559 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2560 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002562 if (asdl_seq_LEN(s->v.If.orelse)) {
2563 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 compiler_use_next_block(c, next);
2565 VISIT_SEQ(c, stmt, s->v.If.orelse);
2566 }
2567 }
2568 compiler_use_next_block(c, end);
2569 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570}
2571
2572static int
2573compiler_for(struct compiler *c, stmt_ty s)
2574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 start = compiler_new_block(c);
2578 cleanup = compiler_new_block(c);
2579 end = compiler_new_block(c);
2580 if (start == NULL || end == NULL || cleanup == NULL)
2581 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002582
2583 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 VISIT(c, expr, s->v.For.iter);
2587 ADDOP(c, GET_ITER);
2588 compiler_use_next_block(c, start);
2589 ADDOP_JREL(c, FOR_ITER, cleanup);
2590 VISIT(c, expr, s->v.For.target);
2591 VISIT_SEQ(c, stmt, s->v.For.body);
2592 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2593 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002594
2595 compiler_pop_fblock(c, FOR_LOOP, start);
2596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 VISIT_SEQ(c, stmt, s->v.For.orelse);
2598 compiler_use_next_block(c, end);
2599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600}
2601
Yury Selivanov75445082015-05-11 22:57:16 -04002602
2603static int
2604compiler_async_for(struct compiler *c, stmt_ty s)
2605{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002606 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002607 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2608 return compiler_error(c, "'async for' outside async function");
2609 }
2610
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002611 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002612 except = compiler_new_block(c);
2613 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002614
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002615 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002616 return 0;
2617
2618 VISIT(c, expr, s->v.AsyncFor.iter);
2619 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002620
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002621 compiler_use_next_block(c, start);
2622 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2623 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002624
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002625 /* SETUP_FINALLY to guard the __anext__ call */
2626 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002627 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002628 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002629 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002630 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002631
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002632 /* Success block for __anext__ */
2633 VISIT(c, expr, s->v.AsyncFor.target);
2634 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2635 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2636
2637 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002638
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002639 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002640 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002641 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002642
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002643 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002644 VISIT_SEQ(c, stmt, s->v.For.orelse);
2645
2646 compiler_use_next_block(c, end);
2647
2648 return 1;
2649}
2650
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651static int
2652compiler_while(struct compiler *c, stmt_ty s)
2653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002655 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (constant == 0) {
2658 if (s->v.While.orelse)
2659 VISIT_SEQ(c, stmt, s->v.While.orelse);
2660 return 1;
2661 }
2662 loop = compiler_new_block(c);
2663 end = compiler_new_block(c);
2664 if (constant == -1) {
2665 anchor = compiler_new_block(c);
2666 if (anchor == NULL)
2667 return 0;
2668 }
2669 if (loop == NULL || end == NULL)
2670 return 0;
2671 if (s->v.While.orelse) {
2672 orelse = compiler_new_block(c);
2673 if (orelse == NULL)
2674 return 0;
2675 }
2676 else
2677 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002680 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 return 0;
2682 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002683 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2684 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
2686 VISIT_SEQ(c, stmt, s->v.While.body);
2687 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 /* XXX should the two POP instructions be in a separate block
2690 if there is no else clause ?
2691 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002693 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002695 compiler_pop_fblock(c, WHILE_LOOP, loop);
2696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (orelse != NULL) /* what if orelse is just pass? */
2698 VISIT_SEQ(c, stmt, s->v.While.orelse);
2699 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702}
2703
2704static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002705compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002707 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002708 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709 if (c->u->u_ste->ste_type != FunctionBlock)
2710 return compiler_error(c, "'return' outside function");
2711 if (s->v.Return.value != NULL &&
2712 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2713 {
2714 return compiler_error(
2715 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002717 if (preserve_tos) {
2718 VISIT(c, expr, s->v.Return.value);
2719 }
2720 for (int depth = c->u->u_nfblocks; depth--;) {
2721 struct fblockinfo *info = &c->u->u_fblock[depth];
2722
2723 if (!compiler_unwind_fblock(c, info, preserve_tos))
2724 return 0;
2725 }
2726 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002727 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002728 }
2729 else if (!preserve_tos) {
2730 VISIT(c, expr, s->v.Return.value);
2731 }
2732 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735}
2736
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002737static int
2738compiler_break(struct compiler *c)
2739{
2740 for (int depth = c->u->u_nfblocks; depth--;) {
2741 struct fblockinfo *info = &c->u->u_fblock[depth];
2742
2743 if (!compiler_unwind_fblock(c, info, 0))
2744 return 0;
2745 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2746 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2747 return 1;
2748 }
2749 }
2750 return compiler_error(c, "'break' outside loop");
2751}
2752
2753static int
2754compiler_continue(struct compiler *c)
2755{
2756 for (int depth = c->u->u_nfblocks; depth--;) {
2757 struct fblockinfo *info = &c->u->u_fblock[depth];
2758
2759 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2760 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2761 return 1;
2762 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002763 if (!compiler_unwind_fblock(c, info, 0))
2764 return 0;
2765 }
2766 return compiler_error(c, "'continue' not properly in loop");
2767}
2768
2769
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771
2772 SETUP_FINALLY L
2773 <code for body>
2774 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 BEGIN_FINALLY
2776 L:
2777 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 END_FINALLY
2779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002780 The special instructions use the block stack. Each block
2781 stack entry contains the instruction that created it (here
2782 SETUP_FINALLY), the level of the value stack at the time the
2783 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 Pushes the current value stack level and the label
2787 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 Pops en entry from the block stack.
2790 BEGIN_FINALLY
2791 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2794 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002797 when a SETUP_FINALLY entry is found, the raised and the caught
2798 exceptions are pushed onto the value stack (and the exception
2799 condition is cleared), and the interpreter jumps to the label
2800 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801*/
2802
2803static int
2804compiler_try_finally(struct compiler *c, stmt_ty s)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 body = compiler_new_block(c);
2809 end = compiler_new_block(c);
2810 if (body == NULL || end == NULL)
2811 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002813 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 ADDOP_JREL(c, SETUP_FINALLY, end);
2815 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002816 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002818 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2819 if (!compiler_try_except(c, s))
2820 return 0;
2821 }
2822 else {
2823 VISIT_SEQ(c, stmt, s->v.Try.body);
2824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002826 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002829 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002831 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002833 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 ADDOP(c, END_FINALLY);
2835 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837}
2838
2839/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002840 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841 (The contents of the value stack is shown in [], with the top
2842 at the right; 'tb' is trace-back info, 'val' the exception's
2843 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844
2845 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002846 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 [] <code for S>
2848 [] POP_BLOCK
2849 [] JUMP_FORWARD L0
2850
2851 [tb, val, exc] L1: DUP )
2852 [tb, val, exc, exc] <evaluate E1> )
2853 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2854 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2855 [tb, val, exc] POP
2856 [tb, val] <assign to V1> (or POP if no V1)
2857 [tb] POP
2858 [] <code for S1>
2859 JUMP_FORWARD L0
2860
2861 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 .............................etc.......................
2863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2865
2866 [] L0: <next statement>
2867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868 Of course, parts are not generated if Vi or Ei is not present.
2869*/
2870static int
2871compiler_try_except(struct compiler *c, stmt_ty s)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002874 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 body = compiler_new_block(c);
2877 except = compiler_new_block(c);
2878 orelse = compiler_new_block(c);
2879 end = compiler_new_block(c);
2880 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2881 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002882 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002886 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 ADDOP(c, POP_BLOCK);
2888 compiler_pop_fblock(c, EXCEPT, body);
2889 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002890 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 compiler_use_next_block(c, except);
2892 for (i = 0; i < n; i++) {
2893 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002894 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if (!handler->v.ExceptHandler.type && i < n-1)
2896 return compiler_error(c, "default 'except:' must be last");
2897 c->u->u_lineno_set = 0;
2898 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002899 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 except = compiler_new_block(c);
2901 if (except == NULL)
2902 return 0;
2903 if (handler->v.ExceptHandler.type) {
2904 ADDOP(c, DUP_TOP);
2905 VISIT(c, expr, handler->v.ExceptHandler.type);
2906 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2907 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2908 }
2909 ADDOP(c, POP_TOP);
2910 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002911 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002912
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002913 cleanup_end = compiler_new_block(c);
2914 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002915 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002916 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002917 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002918
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002919 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2920 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002922 /*
2923 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002924 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002925 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002926 try:
2927 # body
2928 finally:
2929 name = None
2930 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002931 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002933 /* second try: */
2934 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2935 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002936 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002937 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002939 /* second # body */
2940 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2941 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942 ADDOP(c, BEGIN_FINALLY);
2943 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002945 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002946 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002948 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002951 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002952 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002953 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002955 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002956 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002957 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 }
2959 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002960 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002962 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002963 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002964 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
Guido van Rossumb940e112007-01-10 16:19:56 +00002966 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002967 ADDOP(c, POP_TOP);
2968 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002969 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002970 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002972 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002973 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 }
2975 ADDOP_JREL(c, JUMP_FORWARD, end);
2976 compiler_use_next_block(c, except);
2977 }
2978 ADDOP(c, END_FINALLY);
2979 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002980 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 compiler_use_next_block(c, end);
2982 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002986compiler_try(struct compiler *c, stmt_ty s) {
2987 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2988 return compiler_try_finally(c, s);
2989 else
2990 return compiler_try_except(c, s);
2991}
2992
2993
2994static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995compiler_import_as(struct compiler *c, identifier name, identifier asname)
2996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* The IMPORT_NAME opcode was already generated. This function
2998 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003001 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003003 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3004 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003005 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003006 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003009 while (1) {
3010 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003012 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003014 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003015 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003017 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003018 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003019 if (dot == -1) {
3020 break;
3021 }
3022 ADDOP(c, ROT_TWO);
3023 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003025 if (!compiler_nameop(c, asname, Store)) {
3026 return 0;
3027 }
3028 ADDOP(c, POP_TOP);
3029 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 }
3031 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032}
3033
3034static int
3035compiler_import(struct compiler *c, stmt_ty s)
3036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* The Import node stores a module name like a.b.c as a single
3038 string. This is convenient for all cases except
3039 import a.b.c as d
3040 where we need to parse that string to extract the individual
3041 module names.
3042 XXX Perhaps change the representation to make this case simpler?
3043 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003044 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 for (i = 0; i < n; i++) {
3047 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3048 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003050 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3051 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (alias->asname) {
3055 r = compiler_import_as(c, alias->name, alias->asname);
3056 if (!r)
3057 return r;
3058 }
3059 else {
3060 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 Py_ssize_t dot = PyUnicode_FindChar(
3062 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003063 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003064 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003065 if (tmp == NULL)
3066 return 0;
3067 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003069 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 Py_DECREF(tmp);
3071 }
3072 if (!r)
3073 return r;
3074 }
3075 }
3076 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077}
3078
3079static int
3080compiler_from_import(struct compiler *c, stmt_ty s)
3081{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003082 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003083 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 if (!empty_string) {
3087 empty_string = PyUnicode_FromString("");
3088 if (!empty_string)
3089 return 0;
3090 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003092 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003093
3094 names = PyTuple_New(n);
3095 if (!names)
3096 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 /* build up the names */
3099 for (i = 0; i < n; i++) {
3100 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3101 Py_INCREF(alias->name);
3102 PyTuple_SET_ITEM(names, i, alias->name);
3103 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003106 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 Py_DECREF(names);
3108 return compiler_error(c, "from __future__ imports must occur "
3109 "at the beginning of the file");
3110 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003111 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 if (s->v.ImportFrom.module) {
3114 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3115 }
3116 else {
3117 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3118 }
3119 for (i = 0; i < n; i++) {
3120 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3121 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003123 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 assert(n == 1);
3125 ADDOP(c, IMPORT_STAR);
3126 return 1;
3127 }
3128
3129 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3130 store_name = alias->name;
3131 if (alias->asname)
3132 store_name = alias->asname;
3133
3134 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 return 0;
3136 }
3137 }
3138 /* remove imported module */
3139 ADDOP(c, POP_TOP);
3140 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141}
3142
3143static int
3144compiler_assert(struct compiler *c, stmt_ty s)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 static PyObject *assertion_error = NULL;
3147 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
Georg Brandl8334fd92010-12-04 10:26:46 +00003149 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 return 1;
3151 if (assertion_error == NULL) {
3152 assertion_error = PyUnicode_InternFromString("AssertionError");
3153 if (assertion_error == NULL)
3154 return 0;
3155 }
3156 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003157 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3158 {
3159 if (!compiler_warn(c, "assertion is always true, "
3160 "perhaps remove parentheses?"))
3161 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003162 return 0;
3163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 end = compiler_new_block(c);
3166 if (end == NULL)
3167 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003168 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3169 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3171 if (s->v.Assert.msg) {
3172 VISIT(c, expr, s->v.Assert.msg);
3173 ADDOP_I(c, CALL_FUNCTION, 1);
3174 }
3175 ADDOP_I(c, RAISE_VARARGS, 1);
3176 compiler_use_next_block(c, end);
3177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178}
3179
3180static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003181compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3182{
3183 if (c->c_interactive && c->c_nestlevel <= 1) {
3184 VISIT(c, expr, value);
3185 ADDOP(c, PRINT_EXPR);
3186 return 1;
3187 }
3188
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003189 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003190 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003191 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003192 }
3193
3194 VISIT(c, expr, value);
3195 ADDOP(c, POP_TOP);
3196 return 1;
3197}
3198
3199static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200compiler_visit_stmt(struct compiler *c, stmt_ty s)
3201{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003202 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* Always assign a lineno to the next instruction for a stmt. */
3205 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003206 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 switch (s->kind) {
3210 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003211 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 case ClassDef_kind:
3213 return compiler_class(c, s);
3214 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003215 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 case Delete_kind:
3217 VISIT_SEQ(c, expr, s->v.Delete.targets)
3218 break;
3219 case Assign_kind:
3220 n = asdl_seq_LEN(s->v.Assign.targets);
3221 VISIT(c, expr, s->v.Assign.value);
3222 for (i = 0; i < n; i++) {
3223 if (i < n - 1)
3224 ADDOP(c, DUP_TOP);
3225 VISIT(c, expr,
3226 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3227 }
3228 break;
3229 case AugAssign_kind:
3230 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003231 case AnnAssign_kind:
3232 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 case For_kind:
3234 return compiler_for(c, s);
3235 case While_kind:
3236 return compiler_while(c, s);
3237 case If_kind:
3238 return compiler_if(c, s);
3239 case Raise_kind:
3240 n = 0;
3241 if (s->v.Raise.exc) {
3242 VISIT(c, expr, s->v.Raise.exc);
3243 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003244 if (s->v.Raise.cause) {
3245 VISIT(c, expr, s->v.Raise.cause);
3246 n++;
3247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003249 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003251 case Try_kind:
3252 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 case Assert_kind:
3254 return compiler_assert(c, s);
3255 case Import_kind:
3256 return compiler_import(c, s);
3257 case ImportFrom_kind:
3258 return compiler_from_import(c, s);
3259 case Global_kind:
3260 case Nonlocal_kind:
3261 break;
3262 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003263 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 case Pass_kind:
3265 break;
3266 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003267 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 case Continue_kind:
3269 return compiler_continue(c);
3270 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003271 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003272 case AsyncFunctionDef_kind:
3273 return compiler_function(c, s, 1);
3274 case AsyncWith_kind:
3275 return compiler_async_with(c, s, 0);
3276 case AsyncFor_kind:
3277 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 }
Yury Selivanov75445082015-05-11 22:57:16 -04003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281}
3282
3283static int
3284unaryop(unaryop_ty op)
3285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 switch (op) {
3287 case Invert:
3288 return UNARY_INVERT;
3289 case Not:
3290 return UNARY_NOT;
3291 case UAdd:
3292 return UNARY_POSITIVE;
3293 case USub:
3294 return UNARY_NEGATIVE;
3295 default:
3296 PyErr_Format(PyExc_SystemError,
3297 "unary op %d should not be possible", op);
3298 return 0;
3299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300}
3301
3302static int
3303binop(struct compiler *c, operator_ty op)
3304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 switch (op) {
3306 case Add:
3307 return BINARY_ADD;
3308 case Sub:
3309 return BINARY_SUBTRACT;
3310 case Mult:
3311 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003312 case MatMult:
3313 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 case Div:
3315 return BINARY_TRUE_DIVIDE;
3316 case Mod:
3317 return BINARY_MODULO;
3318 case Pow:
3319 return BINARY_POWER;
3320 case LShift:
3321 return BINARY_LSHIFT;
3322 case RShift:
3323 return BINARY_RSHIFT;
3324 case BitOr:
3325 return BINARY_OR;
3326 case BitXor:
3327 return BINARY_XOR;
3328 case BitAnd:
3329 return BINARY_AND;
3330 case FloorDiv:
3331 return BINARY_FLOOR_DIVIDE;
3332 default:
3333 PyErr_Format(PyExc_SystemError,
3334 "binary op %d should not be possible", op);
3335 return 0;
3336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337}
3338
3339static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340inplace_binop(struct compiler *c, operator_ty op)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 switch (op) {
3343 case Add:
3344 return INPLACE_ADD;
3345 case Sub:
3346 return INPLACE_SUBTRACT;
3347 case Mult:
3348 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003349 case MatMult:
3350 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 case Div:
3352 return INPLACE_TRUE_DIVIDE;
3353 case Mod:
3354 return INPLACE_MODULO;
3355 case Pow:
3356 return INPLACE_POWER;
3357 case LShift:
3358 return INPLACE_LSHIFT;
3359 case RShift:
3360 return INPLACE_RSHIFT;
3361 case BitOr:
3362 return INPLACE_OR;
3363 case BitXor:
3364 return INPLACE_XOR;
3365 case BitAnd:
3366 return INPLACE_AND;
3367 case FloorDiv:
3368 return INPLACE_FLOOR_DIVIDE;
3369 default:
3370 PyErr_Format(PyExc_SystemError,
3371 "inplace binary op %d should not be possible", op);
3372 return 0;
3373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374}
3375
3376static int
3377compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3378{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003379 int op, scope;
3380 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 PyObject *dict = c->u->u_names;
3384 PyObject *mangled;
3385 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003387 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3388 !_PyUnicode_EqualToASCIIString(name, "True") &&
3389 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003390
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003391 mangled = _Py_Mangle(c->u->u_private, name);
3392 if (!mangled)
3393 return 0;
3394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 op = 0;
3396 optype = OP_NAME;
3397 scope = PyST_GetScope(c->u->u_ste, mangled);
3398 switch (scope) {
3399 case FREE:
3400 dict = c->u->u_freevars;
3401 optype = OP_DEREF;
3402 break;
3403 case CELL:
3404 dict = c->u->u_cellvars;
3405 optype = OP_DEREF;
3406 break;
3407 case LOCAL:
3408 if (c->u->u_ste->ste_type == FunctionBlock)
3409 optype = OP_FAST;
3410 break;
3411 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003412 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 optype = OP_GLOBAL;
3414 break;
3415 case GLOBAL_EXPLICIT:
3416 optype = OP_GLOBAL;
3417 break;
3418 default:
3419 /* scope can be 0 */
3420 break;
3421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 switch (optype) {
3427 case OP_DEREF:
3428 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003429 case Load:
3430 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3431 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003432 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003433 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:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003450 op = STORE_FAST;
3451 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 case Del: op = DELETE_FAST; break;
3453 case AugLoad:
3454 case AugStore:
3455 break;
3456 case Param:
3457 default:
3458 PyErr_SetString(PyExc_SystemError,
3459 "param invalid for local variable");
3460 return 0;
3461 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003462 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return 1;
3464 case OP_GLOBAL:
3465 switch (ctx) {
3466 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003467 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003468 op = STORE_GLOBAL;
3469 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 case Del: op = DELETE_GLOBAL; break;
3471 case AugLoad:
3472 case AugStore:
3473 break;
3474 case Param:
3475 default:
3476 PyErr_SetString(PyExc_SystemError,
3477 "param invalid for global variable");
3478 return 0;
3479 }
3480 break;
3481 case OP_NAME:
3482 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003483 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003484 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003485 op = STORE_NAME;
3486 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 case Del: op = DELETE_NAME; break;
3488 case AugLoad:
3489 case AugStore:
3490 break;
3491 case Param:
3492 default:
3493 PyErr_SetString(PyExc_SystemError,
3494 "param invalid for name variable");
3495 return 0;
3496 }
3497 break;
3498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 assert(op);
3501 arg = compiler_add_o(c, dict, mangled);
3502 Py_DECREF(mangled);
3503 if (arg < 0)
3504 return 0;
3505 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506}
3507
3508static int
3509compiler_boolop(struct compiler *c, expr_ty e)
3510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003512 int jumpi;
3513 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 assert(e->kind == BoolOp_kind);
3517 if (e->v.BoolOp.op == And)
3518 jumpi = JUMP_IF_FALSE_OR_POP;
3519 else
3520 jumpi = JUMP_IF_TRUE_OR_POP;
3521 end = compiler_new_block(c);
3522 if (end == NULL)
3523 return 0;
3524 s = e->v.BoolOp.values;
3525 n = asdl_seq_LEN(s) - 1;
3526 assert(n >= 0);
3527 for (i = 0; i < n; ++i) {
3528 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3529 ADDOP_JABS(c, jumpi, end);
3530 }
3531 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3532 compiler_use_next_block(c, end);
3533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534}
3535
3536static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537starunpack_helper(struct compiler *c, asdl_seq *elts,
3538 int single_op, int inner_op, int outer_op)
3539{
3540 Py_ssize_t n = asdl_seq_LEN(elts);
3541 Py_ssize_t i, nsubitems = 0, nseen = 0;
3542 for (i = 0; i < n; i++) {
3543 expr_ty elt = asdl_seq_GET(elts, i);
3544 if (elt->kind == Starred_kind) {
3545 if (nseen) {
3546 ADDOP_I(c, inner_op, nseen);
3547 nseen = 0;
3548 nsubitems++;
3549 }
3550 VISIT(c, expr, elt->v.Starred.value);
3551 nsubitems++;
3552 }
3553 else {
3554 VISIT(c, expr, elt);
3555 nseen++;
3556 }
3557 }
3558 if (nsubitems) {
3559 if (nseen) {
3560 ADDOP_I(c, inner_op, nseen);
3561 nsubitems++;
3562 }
3563 ADDOP_I(c, outer_op, nsubitems);
3564 }
3565 else
3566 ADDOP_I(c, single_op, nseen);
3567 return 1;
3568}
3569
3570static int
3571assignment_helper(struct compiler *c, asdl_seq *elts)
3572{
3573 Py_ssize_t n = asdl_seq_LEN(elts);
3574 Py_ssize_t i;
3575 int seen_star = 0;
3576 for (i = 0; i < n; i++) {
3577 expr_ty elt = asdl_seq_GET(elts, i);
3578 if (elt->kind == Starred_kind && !seen_star) {
3579 if ((i >= (1 << 8)) ||
3580 (n-i-1 >= (INT_MAX >> 8)))
3581 return compiler_error(c,
3582 "too many expressions in "
3583 "star-unpacking assignment");
3584 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3585 seen_star = 1;
3586 asdl_seq_SET(elts, i, elt->v.Starred.value);
3587 }
3588 else if (elt->kind == Starred_kind) {
3589 return compiler_error(c,
3590 "two starred expressions in assignment");
3591 }
3592 }
3593 if (!seen_star) {
3594 ADDOP_I(c, UNPACK_SEQUENCE, n);
3595 }
3596 VISIT_SEQ(c, expr, elts);
3597 return 1;
3598}
3599
3600static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601compiler_list(struct compiler *c, expr_ty e)
3602{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003603 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003604 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003605 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003607 else if (e->v.List.ctx == Load) {
3608 return starunpack_helper(c, elts,
3609 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003611 else
3612 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614}
3615
3616static int
3617compiler_tuple(struct compiler *c, expr_ty e)
3618{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003619 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003620 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003621 return assignment_helper(c, elts);
3622 }
3623 else if (e->v.Tuple.ctx == Load) {
3624 return starunpack_helper(c, elts,
3625 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3626 }
3627 else
3628 VISIT_SEQ(c, expr, elts);
3629 return 1;
3630}
3631
3632static int
3633compiler_set(struct compiler *c, expr_ty e)
3634{
3635 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3636 BUILD_SET, BUILD_SET_UNPACK);
3637}
3638
3639static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003640are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3641{
3642 Py_ssize_t i;
3643 for (i = begin; i < end; i++) {
3644 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003645 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003646 return 0;
3647 }
3648 return 1;
3649}
3650
3651static int
3652compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3653{
3654 Py_ssize_t i, n = end - begin;
3655 PyObject *keys, *key;
3656 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3657 for (i = begin; i < end; i++) {
3658 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3659 }
3660 keys = PyTuple_New(n);
3661 if (keys == NULL) {
3662 return 0;
3663 }
3664 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003665 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003666 Py_INCREF(key);
3667 PyTuple_SET_ITEM(keys, i - begin, key);
3668 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003669 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003670 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3671 }
3672 else {
3673 for (i = begin; i < end; i++) {
3674 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3675 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3676 }
3677 ADDOP_I(c, BUILD_MAP, n);
3678 }
3679 return 1;
3680}
3681
3682static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003683compiler_dict(struct compiler *c, expr_ty e)
3684{
Victor Stinner976bb402016-03-23 11:36:19 +01003685 Py_ssize_t i, n, elements;
3686 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 int is_unpacking = 0;
3688 n = asdl_seq_LEN(e->v.Dict.values);
3689 containers = 0;
3690 elements = 0;
3691 for (i = 0; i < n; i++) {
3692 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3693 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003694 if (!compiler_subdict(c, e, i - elements, i))
3695 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003696 containers++;
3697 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003699 if (is_unpacking) {
3700 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3701 containers++;
3702 }
3703 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003704 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 }
3706 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003707 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003708 if (!compiler_subdict(c, e, n - elements, n))
3709 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 containers++;
3711 }
3712 /* If there is more than one dict, they need to be merged into a new
3713 * dict. If there is one dict and it's an unpacking, then it needs
3714 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003715 if (containers > 1 || is_unpacking) {
3716 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 }
3718 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719}
3720
3721static int
3722compiler_compare(struct compiler *c, expr_ty e)
3723{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003724 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003726 if (!check_compare(c, e)) {
3727 return 0;
3728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003730 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3731 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3732 if (n == 0) {
3733 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3734 ADDOP_I(c, COMPARE_OP,
3735 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3736 }
3737 else {
3738 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 if (cleanup == NULL)
3740 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003741 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 VISIT(c, expr,
3743 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003744 ADDOP(c, DUP_TOP);
3745 ADDOP(c, ROT_THREE);
3746 ADDOP_I(c, COMPARE_OP,
3747 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3748 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3749 NEXT_BLOCK(c);
3750 }
3751 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3752 ADDOP_I(c, COMPARE_OP,
3753 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 basicblock *end = compiler_new_block(c);
3755 if (end == NULL)
3756 return 0;
3757 ADDOP_JREL(c, JUMP_FORWARD, end);
3758 compiler_use_next_block(c, cleanup);
3759 ADDOP(c, ROT_TWO);
3760 ADDOP(c, POP_TOP);
3761 compiler_use_next_block(c, end);
3762 }
3763 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764}
3765
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003766static PyTypeObject *
3767infer_type(expr_ty e)
3768{
3769 switch (e->kind) {
3770 case Tuple_kind:
3771 return &PyTuple_Type;
3772 case List_kind:
3773 case ListComp_kind:
3774 return &PyList_Type;
3775 case Dict_kind:
3776 case DictComp_kind:
3777 return &PyDict_Type;
3778 case Set_kind:
3779 case SetComp_kind:
3780 return &PySet_Type;
3781 case GeneratorExp_kind:
3782 return &PyGen_Type;
3783 case Lambda_kind:
3784 return &PyFunction_Type;
3785 case JoinedStr_kind:
3786 case FormattedValue_kind:
3787 return &PyUnicode_Type;
3788 case Constant_kind:
3789 return e->v.Constant.value->ob_type;
3790 default:
3791 return NULL;
3792 }
3793}
3794
3795static int
3796check_caller(struct compiler *c, expr_ty e)
3797{
3798 switch (e->kind) {
3799 case Constant_kind:
3800 case Tuple_kind:
3801 case List_kind:
3802 case ListComp_kind:
3803 case Dict_kind:
3804 case DictComp_kind:
3805 case Set_kind:
3806 case SetComp_kind:
3807 case GeneratorExp_kind:
3808 case JoinedStr_kind:
3809 case FormattedValue_kind:
3810 return compiler_warn(c, "'%.200s' object is not callable; "
3811 "perhaps you missed a comma?",
3812 infer_type(e)->tp_name);
3813 default:
3814 return 1;
3815 }
3816}
3817
3818static int
3819check_subscripter(struct compiler *c, expr_ty e)
3820{
3821 PyObject *v;
3822
3823 switch (e->kind) {
3824 case Constant_kind:
3825 v = e->v.Constant.value;
3826 if (!(v == Py_None || v == Py_Ellipsis ||
3827 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3828 PyAnySet_Check(v)))
3829 {
3830 return 1;
3831 }
3832 /* fall through */
3833 case Set_kind:
3834 case SetComp_kind:
3835 case GeneratorExp_kind:
3836 case Lambda_kind:
3837 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3838 "perhaps you missed a comma?",
3839 infer_type(e)->tp_name);
3840 default:
3841 return 1;
3842 }
3843}
3844
3845static int
3846check_index(struct compiler *c, expr_ty e, slice_ty s)
3847{
3848 PyObject *v;
3849
3850 if (s->kind != Index_kind) {
3851 return 1;
3852 }
3853 PyTypeObject *index_type = infer_type(s->v.Index.value);
3854 if (index_type == NULL
3855 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3856 || index_type == &PySlice_Type) {
3857 return 1;
3858 }
3859
3860 switch (e->kind) {
3861 case Constant_kind:
3862 v = e->v.Constant.value;
3863 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3864 return 1;
3865 }
3866 /* fall through */
3867 case Tuple_kind:
3868 case List_kind:
3869 case ListComp_kind:
3870 case JoinedStr_kind:
3871 case FormattedValue_kind:
3872 return compiler_warn(c, "%.200s indices must be integers or slices, "
3873 "not %.200s; "
3874 "perhaps you missed a comma?",
3875 infer_type(e)->tp_name,
3876 index_type->tp_name);
3877 default:
3878 return 1;
3879 }
3880}
3881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003883maybe_optimize_method_call(struct compiler *c, expr_ty e)
3884{
3885 Py_ssize_t argsl, i;
3886 expr_ty meth = e->v.Call.func;
3887 asdl_seq *args = e->v.Call.args;
3888
3889 /* Check that the call node is an attribute access, and that
3890 the call doesn't have keyword parameters. */
3891 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3892 asdl_seq_LEN(e->v.Call.keywords))
3893 return -1;
3894
3895 /* Check that there are no *varargs types of arguments. */
3896 argsl = asdl_seq_LEN(args);
3897 for (i = 0; i < argsl; i++) {
3898 expr_ty elt = asdl_seq_GET(args, i);
3899 if (elt->kind == Starred_kind) {
3900 return -1;
3901 }
3902 }
3903
3904 /* Alright, we can optimize the code. */
3905 VISIT(c, expr, meth->v.Attribute.value);
3906 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3907 VISIT_SEQ(c, expr, e->v.Call.args);
3908 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3909 return 1;
3910}
3911
3912static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913compiler_call(struct compiler *c, expr_ty e)
3914{
Yury Selivanovf2392132016-12-13 19:03:51 -05003915 if (maybe_optimize_method_call(c, e) > 0)
3916 return 1;
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003917 if (!check_caller(c, e->v.Call.func)) {
3918 return 0;
3919 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 VISIT(c, expr, e->v.Call.func);
3921 return compiler_call_helper(c, 0,
3922 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003923 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003924}
3925
Eric V. Smith235a6f02015-09-19 14:51:32 -04003926static int
3927compiler_joined_str(struct compiler *c, expr_ty e)
3928{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003929 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003930 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3931 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003932 return 1;
3933}
3934
Eric V. Smitha78c7952015-11-03 12:45:05 -05003935/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003936static int
3937compiler_formatted_value(struct compiler *c, expr_ty e)
3938{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003939 /* Our oparg encodes 2 pieces of information: the conversion
3940 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003941
Eric V. Smitha78c7952015-11-03 12:45:05 -05003942 Convert the conversion char to 2 bits:
3943 None: 000 0x0 FVC_NONE
3944 !s : 001 0x1 FVC_STR
3945 !r : 010 0x2 FVC_REPR
3946 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003947
Eric V. Smitha78c7952015-11-03 12:45:05 -05003948 next bit is whether or not we have a format spec:
3949 yes : 100 0x4
3950 no : 000 0x0
3951 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003952
Eric V. Smitha78c7952015-11-03 12:45:05 -05003953 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003954
Eric V. Smitha78c7952015-11-03 12:45:05 -05003955 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003956 VISIT(c, expr, e->v.FormattedValue.value);
3957
Eric V. Smitha78c7952015-11-03 12:45:05 -05003958 switch (e->v.FormattedValue.conversion) {
3959 case 's': oparg = FVC_STR; break;
3960 case 'r': oparg = FVC_REPR; break;
3961 case 'a': oparg = FVC_ASCII; break;
3962 case -1: oparg = FVC_NONE; break;
3963 default:
3964 PyErr_SetString(PyExc_SystemError,
3965 "Unrecognized conversion character");
3966 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003967 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003968 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003969 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003970 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003971 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003972 }
3973
Eric V. Smitha78c7952015-11-03 12:45:05 -05003974 /* And push our opcode and oparg */
3975 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003976 return 1;
3977}
3978
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003979static int
3980compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3981{
3982 Py_ssize_t i, n = end - begin;
3983 keyword_ty kw;
3984 PyObject *keys, *key;
3985 assert(n > 0);
3986 if (n > 1) {
3987 for (i = begin; i < end; i++) {
3988 kw = asdl_seq_GET(keywords, i);
3989 VISIT(c, expr, kw->value);
3990 }
3991 keys = PyTuple_New(n);
3992 if (keys == NULL) {
3993 return 0;
3994 }
3995 for (i = begin; i < end; i++) {
3996 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3997 Py_INCREF(key);
3998 PyTuple_SET_ITEM(keys, i - begin, key);
3999 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004000 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004001 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4002 }
4003 else {
4004 /* a for loop only executes once */
4005 for (i = begin; i < end; i++) {
4006 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004007 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004008 VISIT(c, expr, kw->value);
4009 }
4010 ADDOP_I(c, BUILD_MAP, n);
4011 }
4012 return 1;
4013}
4014
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004015/* shared code between compiler_call and compiler_class */
4016static int
4017compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004018 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004019 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004020 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004021{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004022 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004023 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004024
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004025 /* the number of tuples and dictionaries on the stack */
4026 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4027
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004028 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004029 nkwelts = asdl_seq_LEN(keywords);
4030
4031 for (i = 0; i < nkwelts; i++) {
4032 keyword_ty kw = asdl_seq_GET(keywords, i);
4033 if (kw->arg == NULL) {
4034 mustdictunpack = 1;
4035 break;
4036 }
4037 }
4038
4039 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004040 for (i = 0; i < nelts; i++) {
4041 expr_ty elt = asdl_seq_GET(args, i);
4042 if (elt->kind == Starred_kind) {
4043 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004044 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004045 if (nseen) {
4046 ADDOP_I(c, BUILD_TUPLE, nseen);
4047 nseen = 0;
4048 nsubargs++;
4049 }
4050 VISIT(c, expr, elt->v.Starred.value);
4051 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004052 }
4053 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004054 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004055 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004056 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004058
4059 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004060 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004061 if (nseen) {
4062 /* Pack up any trailing positional arguments. */
4063 ADDOP_I(c, BUILD_TUPLE, nseen);
4064 nsubargs++;
4065 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004066 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004067 /* If we ended up with more than one stararg, we need
4068 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004069 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004070 }
4071 else if (nsubargs == 0) {
4072 ADDOP_I(c, BUILD_TUPLE, 0);
4073 }
4074 nseen = 0; /* the number of keyword arguments on the stack following */
4075 for (i = 0; i < nkwelts; i++) {
4076 keyword_ty kw = asdl_seq_GET(keywords, i);
4077 if (kw->arg == NULL) {
4078 /* A keyword argument unpacking. */
4079 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004080 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4081 return 0;
4082 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004083 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004084 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004085 VISIT(c, expr, kw->value);
4086 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004087 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004088 else {
4089 nseen++;
4090 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004091 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004092 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004093 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004094 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004095 return 0;
4096 nsubkwargs++;
4097 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004098 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004099 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004100 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004101 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004102 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4103 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004105 else if (nkwelts) {
4106 PyObject *names;
4107 VISIT_SEQ(c, keyword, keywords);
4108 names = PyTuple_New(nkwelts);
4109 if (names == NULL) {
4110 return 0;
4111 }
4112 for (i = 0; i < nkwelts; i++) {
4113 keyword_ty kw = asdl_seq_GET(keywords, i);
4114 Py_INCREF(kw->arg);
4115 PyTuple_SET_ITEM(names, i, kw->arg);
4116 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004117 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004118 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4119 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004121 else {
4122 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4123 return 1;
4124 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004125}
4126
Nick Coghlan650f0d02007-04-15 12:05:43 +00004127
4128/* List and set comprehensions and generator expressions work by creating a
4129 nested function to perform the actual iteration. This means that the
4130 iteration variables don't leak into the current scope.
4131 The defined function is called immediately following its definition, with the
4132 result of that call being the result of the expression.
4133 The LC/SC version returns the populated container, while the GE version is
4134 flagged in symtable.c as a generator, so it returns the generator object
4135 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004136
4137 Possible cleanups:
4138 - iterate over the generator sequence instead of using recursion
4139*/
4140
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143compiler_comprehension_generator(struct compiler *c,
4144 asdl_seq *generators, int gen_index,
4145 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004147 comprehension_ty gen;
4148 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4149 if (gen->is_async) {
4150 return compiler_async_comprehension_generator(
4151 c, generators, gen_index, elt, val, type);
4152 } else {
4153 return compiler_sync_comprehension_generator(
4154 c, generators, gen_index, elt, val, type);
4155 }
4156}
4157
4158static int
4159compiler_sync_comprehension_generator(struct compiler *c,
4160 asdl_seq *generators, int gen_index,
4161 expr_ty elt, expr_ty val, int type)
4162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 /* generate code for the iterator, then each of the ifs,
4164 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 comprehension_ty gen;
4167 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004168 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 start = compiler_new_block(c);
4171 skip = compiler_new_block(c);
4172 if_cleanup = compiler_new_block(c);
4173 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4176 anchor == NULL)
4177 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 if (gen_index == 0) {
4182 /* Receive outermost iter as an implicit argument */
4183 c->u->u_argcount = 1;
4184 ADDOP_I(c, LOAD_FAST, 0);
4185 }
4186 else {
4187 /* Sub-iter - calculate on the fly */
4188 VISIT(c, expr, gen->iter);
4189 ADDOP(c, GET_ITER);
4190 }
4191 compiler_use_next_block(c, start);
4192 ADDOP_JREL(c, FOR_ITER, anchor);
4193 NEXT_BLOCK(c);
4194 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 /* XXX this needs to be cleaned up...a lot! */
4197 n = asdl_seq_LEN(gen->ifs);
4198 for (i = 0; i < n; i++) {
4199 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004200 if (!compiler_jump_if(c, e, if_cleanup, 0))
4201 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 NEXT_BLOCK(c);
4203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 if (++gen_index < asdl_seq_LEN(generators))
4206 if (!compiler_comprehension_generator(c,
4207 generators, gen_index,
4208 elt, val, type))
4209 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 /* only append after the last for generator */
4212 if (gen_index >= asdl_seq_LEN(generators)) {
4213 /* comprehension specific code */
4214 switch (type) {
4215 case COMP_GENEXP:
4216 VISIT(c, expr, elt);
4217 ADDOP(c, YIELD_VALUE);
4218 ADDOP(c, POP_TOP);
4219 break;
4220 case COMP_LISTCOMP:
4221 VISIT(c, expr, elt);
4222 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4223 break;
4224 case COMP_SETCOMP:
4225 VISIT(c, expr, elt);
4226 ADDOP_I(c, SET_ADD, gen_index + 1);
4227 break;
4228 case COMP_DICTCOMP:
4229 /* With 'd[k] = v', v is evaluated before k, so we do
4230 the same. */
4231 VISIT(c, expr, val);
4232 VISIT(c, expr, elt);
4233 ADDOP_I(c, MAP_ADD, gen_index + 1);
4234 break;
4235 default:
4236 return 0;
4237 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 compiler_use_next_block(c, skip);
4240 }
4241 compiler_use_next_block(c, if_cleanup);
4242 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4243 compiler_use_next_block(c, anchor);
4244
4245 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246}
4247
4248static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004249compiler_async_comprehension_generator(struct compiler *c,
4250 asdl_seq *generators, int gen_index,
4251 expr_ty elt, expr_ty val, int type)
4252{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004253 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004254 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004255 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004256 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004257 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004258 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004259
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004260 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004261 return 0;
4262 }
4263
4264 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4265
4266 if (gen_index == 0) {
4267 /* Receive outermost iter as an implicit argument */
4268 c->u->u_argcount = 1;
4269 ADDOP_I(c, LOAD_FAST, 0);
4270 }
4271 else {
4272 /* Sub-iter - calculate on the fly */
4273 VISIT(c, expr, gen->iter);
4274 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004275 }
4276
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004277 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004278
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004279 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004280 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004281 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004282 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004283 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004284 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004285
4286 n = asdl_seq_LEN(gen->ifs);
4287 for (i = 0; i < n; i++) {
4288 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004289 if (!compiler_jump_if(c, e, if_cleanup, 0))
4290 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004291 NEXT_BLOCK(c);
4292 }
4293
4294 if (++gen_index < asdl_seq_LEN(generators))
4295 if (!compiler_comprehension_generator(c,
4296 generators, gen_index,
4297 elt, val, type))
4298 return 0;
4299
4300 /* only append after the last for generator */
4301 if (gen_index >= asdl_seq_LEN(generators)) {
4302 /* comprehension specific code */
4303 switch (type) {
4304 case COMP_GENEXP:
4305 VISIT(c, expr, elt);
4306 ADDOP(c, YIELD_VALUE);
4307 ADDOP(c, POP_TOP);
4308 break;
4309 case COMP_LISTCOMP:
4310 VISIT(c, expr, elt);
4311 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4312 break;
4313 case COMP_SETCOMP:
4314 VISIT(c, expr, elt);
4315 ADDOP_I(c, SET_ADD, gen_index + 1);
4316 break;
4317 case COMP_DICTCOMP:
4318 /* With 'd[k] = v', v is evaluated before k, so we do
4319 the same. */
4320 VISIT(c, expr, val);
4321 VISIT(c, expr, elt);
4322 ADDOP_I(c, MAP_ADD, gen_index + 1);
4323 break;
4324 default:
4325 return 0;
4326 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004327 }
4328 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004329 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4330
4331 compiler_use_next_block(c, except);
4332 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004333
4334 return 1;
4335}
4336
4337static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004338compiler_comprehension(struct compiler *c, expr_ty e, int type,
4339 identifier name, asdl_seq *generators, expr_ty elt,
4340 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004343 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004344 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004345 int is_async_function = c->u->u_ste->ste_coroutine;
4346 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004347
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004348 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004349
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004350 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4351 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004352 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004354 }
4355
4356 is_async_generator = c->u->u_ste->ste_coroutine;
4357
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004358 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004359 compiler_error(c, "asynchronous comprehension outside of "
4360 "an asynchronous function");
4361 goto error_in_scope;
4362 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (type != COMP_GENEXP) {
4365 int op;
4366 switch (type) {
4367 case COMP_LISTCOMP:
4368 op = BUILD_LIST;
4369 break;
4370 case COMP_SETCOMP:
4371 op = BUILD_SET;
4372 break;
4373 case COMP_DICTCOMP:
4374 op = BUILD_MAP;
4375 break;
4376 default:
4377 PyErr_Format(PyExc_SystemError,
4378 "unknown comprehension type %d", type);
4379 goto error_in_scope;
4380 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 ADDOP_I(c, op, 0);
4383 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 if (!compiler_comprehension_generator(c, generators, 0, elt,
4386 val, type))
4387 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 if (type != COMP_GENEXP) {
4390 ADDOP(c, RETURN_VALUE);
4391 }
4392
4393 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004394 qualname = c->u->u_qualname;
4395 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004397 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 goto error;
4399
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004400 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004402 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 Py_DECREF(co);
4404
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004405 VISIT(c, expr, outermost->iter);
4406
4407 if (outermost->is_async) {
4408 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004409 } else {
4410 ADDOP(c, GET_ITER);
4411 }
4412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004414
4415 if (is_async_generator && type != COMP_GENEXP) {
4416 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004417 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004418 ADDOP(c, YIELD_FROM);
4419 }
4420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004422error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004424error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004425 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 Py_XDECREF(co);
4427 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004428}
4429
4430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431compiler_genexp(struct compiler *c, expr_ty e)
4432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 static identifier name;
4434 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004435 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 if (!name)
4437 return 0;
4438 }
4439 assert(e->kind == GeneratorExp_kind);
4440 return compiler_comprehension(c, e, COMP_GENEXP, name,
4441 e->v.GeneratorExp.generators,
4442 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443}
4444
4445static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004446compiler_listcomp(struct compiler *c, expr_ty e)
4447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 static identifier name;
4449 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004450 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 if (!name)
4452 return 0;
4453 }
4454 assert(e->kind == ListComp_kind);
4455 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4456 e->v.ListComp.generators,
4457 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004458}
4459
4460static int
4461compiler_setcomp(struct compiler *c, expr_ty e)
4462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 static identifier name;
4464 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004465 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 if (!name)
4467 return 0;
4468 }
4469 assert(e->kind == SetComp_kind);
4470 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4471 e->v.SetComp.generators,
4472 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004473}
4474
4475
4476static int
4477compiler_dictcomp(struct compiler *c, expr_ty e)
4478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 static identifier name;
4480 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004481 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 if (!name)
4483 return 0;
4484 }
4485 assert(e->kind == DictComp_kind);
4486 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4487 e->v.DictComp.generators,
4488 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004489}
4490
4491
4492static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004493compiler_visit_keyword(struct compiler *c, keyword_ty k)
4494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 VISIT(c, expr, k->value);
4496 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004497}
4498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500 whether they are true or false.
4501
4502 Return values: 1 for true, 0 for false, -1 for non-constant.
4503 */
4504
4505static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004506expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004507{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004508 if (e->kind == Constant_kind) {
4509 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004510 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004511 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004512}
4513
Yury Selivanov75445082015-05-11 22:57:16 -04004514
4515/*
4516 Implements the async with statement.
4517
4518 The semantics outlined in that PEP are as follows:
4519
4520 async with EXPR as VAR:
4521 BLOCK
4522
4523 It is implemented roughly as:
4524
4525 context = EXPR
4526 exit = context.__aexit__ # not calling it
4527 value = await context.__aenter__()
4528 try:
4529 VAR = value # if VAR present in the syntax
4530 BLOCK
4531 finally:
4532 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004533 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004534 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004535 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004536 if not (await exit(*exc)):
4537 raise
4538 */
4539static int
4540compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4541{
4542 basicblock *block, *finally;
4543 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4544
4545 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004546 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4547 return compiler_error(c, "'async with' outside async function");
4548 }
Yury Selivanov75445082015-05-11 22:57:16 -04004549
4550 block = compiler_new_block(c);
4551 finally = compiler_new_block(c);
4552 if (!block || !finally)
4553 return 0;
4554
4555 /* Evaluate EXPR */
4556 VISIT(c, expr, item->context_expr);
4557
4558 ADDOP(c, BEFORE_ASYNC_WITH);
4559 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004560 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004561 ADDOP(c, YIELD_FROM);
4562
4563 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4564
4565 /* SETUP_ASYNC_WITH pushes a finally block. */
4566 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004567 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004568 return 0;
4569 }
4570
4571 if (item->optional_vars) {
4572 VISIT(c, expr, item->optional_vars);
4573 }
4574 else {
4575 /* Discard result from context.__aenter__() */
4576 ADDOP(c, POP_TOP);
4577 }
4578
4579 pos++;
4580 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4581 /* BLOCK code */
4582 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4583 else if (!compiler_async_with(c, s, pos))
4584 return 0;
4585
4586 /* End of try block; start the finally block */
4587 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004588 ADDOP(c, BEGIN_FINALLY);
4589 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004590
Yury Selivanov75445082015-05-11 22:57:16 -04004591 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004592 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004593 return 0;
4594
4595 /* Finally block starts; context.__exit__ is on the stack under
4596 the exception or return information. Just issue our magic
4597 opcode. */
4598 ADDOP(c, WITH_CLEANUP_START);
4599
4600 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004601 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004602 ADDOP(c, YIELD_FROM);
4603
4604 ADDOP(c, WITH_CLEANUP_FINISH);
4605
4606 /* Finally block ends. */
4607 ADDOP(c, END_FINALLY);
4608 compiler_pop_fblock(c, FINALLY_END, finally);
4609 return 1;
4610}
4611
4612
Guido van Rossumc2e20742006-02-27 22:32:47 +00004613/*
4614 Implements the with statement from PEP 343.
4615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004617
4618 with EXPR as VAR:
4619 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620
Guido van Rossumc2e20742006-02-27 22:32:47 +00004621 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622
Thomas Wouters477c8d52006-05-27 19:21:47 +00004623 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004624 exit = context.__exit__ # not calling it
4625 value = context.__enter__()
4626 try:
4627 VAR = value # if VAR present in the syntax
4628 BLOCK
4629 finally:
4630 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004631 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004632 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004633 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004634 exit(*exc)
4635 */
4636static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004637compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004638{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004639 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004640 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004641
4642 assert(s->kind == With_kind);
4643
Guido van Rossumc2e20742006-02-27 22:32:47 +00004644 block = compiler_new_block(c);
4645 finally = compiler_new_block(c);
4646 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004647 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004648
Thomas Wouters477c8d52006-05-27 19:21:47 +00004649 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004650 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004651 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004652
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004653 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004654 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004655 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004656 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004657 }
4658
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004659 if (item->optional_vars) {
4660 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004661 }
4662 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004664 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004665 }
4666
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004667 pos++;
4668 if (pos == asdl_seq_LEN(s->v.With.items))
4669 /* BLOCK code */
4670 VISIT_SEQ(c, stmt, s->v.With.body)
4671 else if (!compiler_with(c, s, pos))
4672 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004673
4674 /* End of try block; start the finally block */
4675 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004676 ADDOP(c, BEGIN_FINALLY);
4677 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004678
Guido van Rossumc2e20742006-02-27 22:32:47 +00004679 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004680 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004681 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004682
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004683 /* Finally block starts; context.__exit__ is on the stack under
4684 the exception or return information. Just issue our magic
4685 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004686 ADDOP(c, WITH_CLEANUP_START);
4687 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004688
4689 /* Finally block ends. */
4690 ADDOP(c, END_FINALLY);
4691 compiler_pop_fblock(c, FINALLY_END, finally);
4692 return 1;
4693}
4694
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004695static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004696compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004699 case NamedExpr_kind:
4700 VISIT(c, expr, e->v.NamedExpr.value);
4701 ADDOP(c, DUP_TOP);
4702 VISIT(c, expr, e->v.NamedExpr.target);
4703 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 case BoolOp_kind:
4705 return compiler_boolop(c, e);
4706 case BinOp_kind:
4707 VISIT(c, expr, e->v.BinOp.left);
4708 VISIT(c, expr, e->v.BinOp.right);
4709 ADDOP(c, binop(c, e->v.BinOp.op));
4710 break;
4711 case UnaryOp_kind:
4712 VISIT(c, expr, e->v.UnaryOp.operand);
4713 ADDOP(c, unaryop(e->v.UnaryOp.op));
4714 break;
4715 case Lambda_kind:
4716 return compiler_lambda(c, e);
4717 case IfExp_kind:
4718 return compiler_ifexp(c, e);
4719 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004720 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004722 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 case GeneratorExp_kind:
4724 return compiler_genexp(c, e);
4725 case ListComp_kind:
4726 return compiler_listcomp(c, e);
4727 case SetComp_kind:
4728 return compiler_setcomp(c, e);
4729 case DictComp_kind:
4730 return compiler_dictcomp(c, e);
4731 case Yield_kind:
4732 if (c->u->u_ste->ste_type != FunctionBlock)
4733 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004734 if (e->v.Yield.value) {
4735 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 }
4737 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004738 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004740 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004742 case YieldFrom_kind:
4743 if (c->u->u_ste->ste_type != FunctionBlock)
4744 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004745
4746 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4747 return compiler_error(c, "'yield from' inside async function");
4748
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004749 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004750 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004751 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004752 ADDOP(c, YIELD_FROM);
4753 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004754 case Await_kind:
4755 if (c->u->u_ste->ste_type != FunctionBlock)
4756 return compiler_error(c, "'await' outside function");
4757
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004758 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4759 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004760 return compiler_error(c, "'await' outside async function");
4761
4762 VISIT(c, expr, e->v.Await.value);
4763 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004764 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004765 ADDOP(c, YIELD_FROM);
4766 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 case Compare_kind:
4768 return compiler_compare(c, e);
4769 case Call_kind:
4770 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004771 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004772 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004773 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004774 case JoinedStr_kind:
4775 return compiler_joined_str(c, e);
4776 case FormattedValue_kind:
4777 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 /* The following exprs can be assignment targets. */
4779 case Attribute_kind:
4780 if (e->v.Attribute.ctx != AugStore)
4781 VISIT(c, expr, e->v.Attribute.value);
4782 switch (e->v.Attribute.ctx) {
4783 case AugLoad:
4784 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004785 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 case Load:
4787 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4788 break;
4789 case AugStore:
4790 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004791 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 case Store:
4793 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4794 break;
4795 case Del:
4796 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4797 break;
4798 case Param:
4799 default:
4800 PyErr_SetString(PyExc_SystemError,
4801 "param invalid in attribute expression");
4802 return 0;
4803 }
4804 break;
4805 case Subscript_kind:
4806 switch (e->v.Subscript.ctx) {
4807 case AugLoad:
4808 VISIT(c, expr, e->v.Subscript.value);
4809 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4810 break;
4811 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004812 if (!check_subscripter(c, e->v.Subscript.value)) {
4813 return 0;
4814 }
4815 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4816 return 0;
4817 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 VISIT(c, expr, e->v.Subscript.value);
4819 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4820 break;
4821 case AugStore:
4822 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4823 break;
4824 case Store:
4825 VISIT(c, expr, e->v.Subscript.value);
4826 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4827 break;
4828 case Del:
4829 VISIT(c, expr, e->v.Subscript.value);
4830 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4831 break;
4832 case Param:
4833 default:
4834 PyErr_SetString(PyExc_SystemError,
4835 "param invalid in subscript expression");
4836 return 0;
4837 }
4838 break;
4839 case Starred_kind:
4840 switch (e->v.Starred.ctx) {
4841 case Store:
4842 /* In all legitimate cases, the Starred node was already replaced
4843 * by compiler_list/compiler_tuple. XXX: is that okay? */
4844 return compiler_error(c,
4845 "starred assignment target must be in a list or tuple");
4846 default:
4847 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004848 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 }
4850 break;
4851 case Name_kind:
4852 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4853 /* child nodes of List and Tuple will have expr_context set */
4854 case List_kind:
4855 return compiler_list(c, e);
4856 case Tuple_kind:
4857 return compiler_tuple(c, e);
4858 }
4859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004860}
4861
4862static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004863compiler_visit_expr(struct compiler *c, expr_ty e)
4864{
4865 /* If expr e has a different line number than the last expr/stmt,
4866 set a new line number for the next instruction.
4867 */
4868 int old_lineno = c->u->u_lineno;
4869 int old_col_offset = c->u->u_col_offset;
4870 if (e->lineno != c->u->u_lineno) {
4871 c->u->u_lineno = e->lineno;
4872 c->u->u_lineno_set = 0;
4873 }
4874 /* Updating the column offset is always harmless. */
4875 c->u->u_col_offset = e->col_offset;
4876
4877 int res = compiler_visit_expr1(c, e);
4878
4879 if (old_lineno != c->u->u_lineno) {
4880 c->u->u_lineno = old_lineno;
4881 c->u->u_lineno_set = 0;
4882 }
4883 c->u->u_col_offset = old_col_offset;
4884 return res;
4885}
4886
4887static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004888compiler_augassign(struct compiler *c, stmt_ty s)
4889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 expr_ty e = s->v.AugAssign.target;
4891 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 switch (e->kind) {
4896 case Attribute_kind:
4897 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004898 AugLoad, e->lineno, e->col_offset,
4899 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 if (auge == NULL)
4901 return 0;
4902 VISIT(c, expr, auge);
4903 VISIT(c, expr, s->v.AugAssign.value);
4904 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4905 auge->v.Attribute.ctx = AugStore;
4906 VISIT(c, expr, auge);
4907 break;
4908 case Subscript_kind:
4909 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004910 AugLoad, e->lineno, e->col_offset,
4911 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 if (auge == NULL)
4913 return 0;
4914 VISIT(c, expr, auge);
4915 VISIT(c, expr, s->v.AugAssign.value);
4916 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4917 auge->v.Subscript.ctx = AugStore;
4918 VISIT(c, expr, auge);
4919 break;
4920 case Name_kind:
4921 if (!compiler_nameop(c, e->v.Name.id, Load))
4922 return 0;
4923 VISIT(c, expr, s->v.AugAssign.value);
4924 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4925 return compiler_nameop(c, e->v.Name.id, Store);
4926 default:
4927 PyErr_Format(PyExc_SystemError,
4928 "invalid node type (%d) for augmented assignment",
4929 e->kind);
4930 return 0;
4931 }
4932 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004933}
4934
4935static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004936check_ann_expr(struct compiler *c, expr_ty e)
4937{
4938 VISIT(c, expr, e);
4939 ADDOP(c, POP_TOP);
4940 return 1;
4941}
4942
4943static int
4944check_annotation(struct compiler *c, stmt_ty s)
4945{
4946 /* Annotations are only evaluated in a module or class. */
4947 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4948 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4949 return check_ann_expr(c, s->v.AnnAssign.annotation);
4950 }
4951 return 1;
4952}
4953
4954static int
4955check_ann_slice(struct compiler *c, slice_ty sl)
4956{
4957 switch(sl->kind) {
4958 case Index_kind:
4959 return check_ann_expr(c, sl->v.Index.value);
4960 case Slice_kind:
4961 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4962 return 0;
4963 }
4964 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4965 return 0;
4966 }
4967 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4968 return 0;
4969 }
4970 break;
4971 default:
4972 PyErr_SetString(PyExc_SystemError,
4973 "unexpected slice kind");
4974 return 0;
4975 }
4976 return 1;
4977}
4978
4979static int
4980check_ann_subscr(struct compiler *c, slice_ty sl)
4981{
4982 /* We check that everything in a subscript is defined at runtime. */
4983 Py_ssize_t i, n;
4984
4985 switch (sl->kind) {
4986 case Index_kind:
4987 case Slice_kind:
4988 if (!check_ann_slice(c, sl)) {
4989 return 0;
4990 }
4991 break;
4992 case ExtSlice_kind:
4993 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4994 for (i = 0; i < n; i++) {
4995 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4996 switch (subsl->kind) {
4997 case Index_kind:
4998 case Slice_kind:
4999 if (!check_ann_slice(c, subsl)) {
5000 return 0;
5001 }
5002 break;
5003 case ExtSlice_kind:
5004 default:
5005 PyErr_SetString(PyExc_SystemError,
5006 "extended slice invalid in nested slice");
5007 return 0;
5008 }
5009 }
5010 break;
5011 default:
5012 PyErr_Format(PyExc_SystemError,
5013 "invalid subscript kind %d", sl->kind);
5014 return 0;
5015 }
5016 return 1;
5017}
5018
5019static int
5020compiler_annassign(struct compiler *c, stmt_ty s)
5021{
5022 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005023 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005024
5025 assert(s->kind == AnnAssign_kind);
5026
5027 /* We perform the actual assignment first. */
5028 if (s->v.AnnAssign.value) {
5029 VISIT(c, expr, s->v.AnnAssign.value);
5030 VISIT(c, expr, targ);
5031 }
5032 switch (targ->kind) {
5033 case Name_kind:
5034 /* If we have a simple name in a module or class, store annotation. */
5035 if (s->v.AnnAssign.simple &&
5036 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5037 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005038 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5039 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5040 }
5041 else {
5042 VISIT(c, expr, s->v.AnnAssign.annotation);
5043 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005044 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005045 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005046 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005047 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005048 }
5049 break;
5050 case Attribute_kind:
5051 if (!s->v.AnnAssign.value &&
5052 !check_ann_expr(c, targ->v.Attribute.value)) {
5053 return 0;
5054 }
5055 break;
5056 case Subscript_kind:
5057 if (!s->v.AnnAssign.value &&
5058 (!check_ann_expr(c, targ->v.Subscript.value) ||
5059 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5060 return 0;
5061 }
5062 break;
5063 default:
5064 PyErr_Format(PyExc_SystemError,
5065 "invalid node type (%d) for annotated assignment",
5066 targ->kind);
5067 return 0;
5068 }
5069 /* Annotation is evaluated last. */
5070 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5071 return 0;
5072 }
5073 return 1;
5074}
5075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005076/* Raises a SyntaxError and returns 0.
5077 If something goes wrong, a different exception may be raised.
5078*/
5079
5080static int
5081compiler_error(struct compiler *c, const char *errstr)
5082{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005083 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005085
Victor Stinner14e461d2013-08-26 22:28:21 +02005086 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 if (!loc) {
5088 Py_INCREF(Py_None);
5089 loc = Py_None;
5090 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005091 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005092 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 if (!u)
5094 goto exit;
5095 v = Py_BuildValue("(zO)", errstr, u);
5096 if (!v)
5097 goto exit;
5098 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005099 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 Py_DECREF(loc);
5101 Py_XDECREF(u);
5102 Py_XDECREF(v);
5103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005104}
5105
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005106/* Emits a SyntaxWarning and returns 1 on success.
5107 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5108 and returns 0.
5109*/
5110static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005111compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005112{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005113 va_list vargs;
5114#ifdef HAVE_STDARG_PROTOTYPES
5115 va_start(vargs, format);
5116#else
5117 va_start(vargs);
5118#endif
5119 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5120 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005121 if (msg == NULL) {
5122 return 0;
5123 }
5124 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5125 c->u->u_lineno, NULL, NULL) < 0)
5126 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005127 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005128 /* Replace the SyntaxWarning exception with a SyntaxError
5129 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005130 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005131 assert(PyUnicode_AsUTF8(msg) != NULL);
5132 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005133 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005134 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005135 return 0;
5136 }
5137 Py_DECREF(msg);
5138 return 1;
5139}
5140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005141static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142compiler_handle_subscr(struct compiler *c, const char *kind,
5143 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 /* XXX this code is duplicated */
5148 switch (ctx) {
5149 case AugLoad: /* fall through to Load */
5150 case Load: op = BINARY_SUBSCR; break;
5151 case AugStore:/* fall through to Store */
5152 case Store: op = STORE_SUBSCR; break;
5153 case Del: op = DELETE_SUBSCR; break;
5154 case Param:
5155 PyErr_Format(PyExc_SystemError,
5156 "invalid %s kind %d in subscript\n",
5157 kind, ctx);
5158 return 0;
5159 }
5160 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005161 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 }
5163 else if (ctx == AugStore) {
5164 ADDOP(c, ROT_THREE);
5165 }
5166 ADDOP(c, op);
5167 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005168}
5169
5170static int
5171compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 int n = 2;
5174 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 /* only handles the cases where BUILD_SLICE is emitted */
5177 if (s->v.Slice.lower) {
5178 VISIT(c, expr, s->v.Slice.lower);
5179 }
5180 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005181 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 if (s->v.Slice.upper) {
5185 VISIT(c, expr, s->v.Slice.upper);
5186 }
5187 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005188 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 }
5190
5191 if (s->v.Slice.step) {
5192 n++;
5193 VISIT(c, expr, s->v.Slice.step);
5194 }
5195 ADDOP_I(c, BUILD_SLICE, n);
5196 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005197}
5198
5199static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5201 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 switch (s->kind) {
5204 case Slice_kind:
5205 return compiler_slice(c, s, ctx);
5206 case Index_kind:
5207 VISIT(c, expr, s->v.Index.value);
5208 break;
5209 case ExtSlice_kind:
5210 default:
5211 PyErr_SetString(PyExc_SystemError,
5212 "extended slice invalid in nested slice");
5213 return 0;
5214 }
5215 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005216}
5217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005218static int
5219compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5220{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005221 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 switch (s->kind) {
5223 case Index_kind:
5224 kindname = "index";
5225 if (ctx != AugStore) {
5226 VISIT(c, expr, s->v.Index.value);
5227 }
5228 break;
5229 case Slice_kind:
5230 kindname = "slice";
5231 if (ctx != AugStore) {
5232 if (!compiler_slice(c, s, ctx))
5233 return 0;
5234 }
5235 break;
5236 case ExtSlice_kind:
5237 kindname = "extended slice";
5238 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005239 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 for (i = 0; i < n; i++) {
5241 slice_ty sub = (slice_ty)asdl_seq_GET(
5242 s->v.ExtSlice.dims, i);
5243 if (!compiler_visit_nested_slice(c, sub, ctx))
5244 return 0;
5245 }
5246 ADDOP_I(c, BUILD_TUPLE, n);
5247 }
5248 break;
5249 default:
5250 PyErr_Format(PyExc_SystemError,
5251 "invalid subscript kind %d", s->kind);
5252 return 0;
5253 }
5254 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005255}
5256
Thomas Wouters89f507f2006-12-13 04:49:30 +00005257/* End of the compiler section, beginning of the assembler section */
5258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005259/* do depth-first search of basic block graph, starting with block.
5260 post records the block indices in post-order.
5261
5262 XXX must handle implicit jumps from one block to next
5263*/
5264
Thomas Wouters89f507f2006-12-13 04:49:30 +00005265struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 PyObject *a_bytecode; /* string containing bytecode */
5267 int a_offset; /* offset into bytecode */
5268 int a_nblocks; /* number of reachable blocks */
5269 basicblock **a_postorder; /* list of blocks in dfs postorder */
5270 PyObject *a_lnotab; /* string containing lnotab */
5271 int a_lnotab_off; /* offset into lnotab */
5272 int a_lineno; /* last lineno of emitted instruction */
5273 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005274};
5275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005276static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005277dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005278{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005279 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005280
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005281 /* Get rid of recursion for normal control flow.
5282 Since the number of blocks is limited, unused space in a_postorder
5283 (from a_nblocks to end) can be used as a stack for still not ordered
5284 blocks. */
5285 for (j = end; b && !b->b_seen; b = b->b_next) {
5286 b->b_seen = 1;
5287 assert(a->a_nblocks < j);
5288 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005290 while (j < end) {
5291 b = a->a_postorder[j++];
5292 for (i = 0; i < b->b_iused; i++) {
5293 struct instr *instr = &b->b_instr[i];
5294 if (instr->i_jrel || instr->i_jabs)
5295 dfs(c, instr->i_target, a, j);
5296 }
5297 assert(a->a_nblocks < j);
5298 a->a_postorder[a->a_nblocks++] = b;
5299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005300}
5301
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005302Py_LOCAL_INLINE(void)
5303stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005304{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005305 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005306 if (b->b_startdepth < depth) {
5307 assert(b->b_startdepth < 0);
5308 b->b_startdepth = depth;
5309 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005311}
5312
5313/* Find the flow path that needs the largest stack. We assume that
5314 * cycles in the flow graph have no net effect on the stack depth.
5315 */
5316static int
5317stackdepth(struct compiler *c)
5318{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005319 basicblock *b, *entryblock = NULL;
5320 basicblock **stack, **sp;
5321 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 b->b_startdepth = INT_MIN;
5324 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005325 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 }
5327 if (!entryblock)
5328 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005329 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5330 if (!stack) {
5331 PyErr_NoMemory();
5332 return -1;
5333 }
5334
5335 sp = stack;
5336 stackdepth_push(&sp, entryblock, 0);
5337 while (sp != stack) {
5338 b = *--sp;
5339 int depth = b->b_startdepth;
5340 assert(depth >= 0);
5341 basicblock *next = b->b_next;
5342 for (int i = 0; i < b->b_iused; i++) {
5343 struct instr *instr = &b->b_instr[i];
5344 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5345 if (effect == PY_INVALID_STACK_EFFECT) {
5346 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5347 Py_FatalError("PyCompile_OpcodeStackEffect()");
5348 }
5349 int new_depth = depth + effect;
5350 if (new_depth > maxdepth) {
5351 maxdepth = new_depth;
5352 }
5353 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5354 if (instr->i_jrel || instr->i_jabs) {
5355 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5356 assert(effect != PY_INVALID_STACK_EFFECT);
5357 int target_depth = depth + effect;
5358 if (target_depth > maxdepth) {
5359 maxdepth = target_depth;
5360 }
5361 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005362 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005363 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005364 assert(instr->i_target->b_startdepth >= target_depth);
5365 depth = new_depth;
5366 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005367 }
5368 stackdepth_push(&sp, instr->i_target, target_depth);
5369 }
5370 depth = new_depth;
5371 if (instr->i_opcode == JUMP_ABSOLUTE ||
5372 instr->i_opcode == JUMP_FORWARD ||
5373 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005374 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005375 {
5376 /* remaining code is dead */
5377 next = NULL;
5378 break;
5379 }
5380 }
5381 if (next != NULL) {
5382 stackdepth_push(&sp, next, depth);
5383 }
5384 }
5385 PyObject_Free(stack);
5386 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387}
5388
5389static int
5390assemble_init(struct assembler *a, int nblocks, int firstlineno)
5391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 memset(a, 0, sizeof(struct assembler));
5393 a->a_lineno = firstlineno;
5394 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5395 if (!a->a_bytecode)
5396 return 0;
5397 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5398 if (!a->a_lnotab)
5399 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005400 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 PyErr_NoMemory();
5402 return 0;
5403 }
5404 a->a_postorder = (basicblock **)PyObject_Malloc(
5405 sizeof(basicblock *) * nblocks);
5406 if (!a->a_postorder) {
5407 PyErr_NoMemory();
5408 return 0;
5409 }
5410 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005411}
5412
5413static void
5414assemble_free(struct assembler *a)
5415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 Py_XDECREF(a->a_bytecode);
5417 Py_XDECREF(a->a_lnotab);
5418 if (a->a_postorder)
5419 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420}
5421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005422static int
5423blocksize(basicblock *b)
5424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 int i;
5426 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005429 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431}
5432
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005433/* Appends a pair to the end of the line number table, a_lnotab, representing
5434 the instruction's bytecode offset and line number. See
5435 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005436
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005437static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005438assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005441 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005443
Serhiy Storchakaab874002016-09-11 13:48:15 +03005444 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 if(d_bytecode == 0 && d_lineno == 0)
5450 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 if (d_bytecode > 255) {
5453 int j, nbytes, ncodes = d_bytecode / 255;
5454 nbytes = a->a_lnotab_off + 2 * ncodes;
5455 len = PyBytes_GET_SIZE(a->a_lnotab);
5456 if (nbytes >= len) {
5457 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5458 len = nbytes;
5459 else if (len <= INT_MAX / 2)
5460 len *= 2;
5461 else {
5462 PyErr_NoMemory();
5463 return 0;
5464 }
5465 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5466 return 0;
5467 }
5468 lnotab = (unsigned char *)
5469 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5470 for (j = 0; j < ncodes; j++) {
5471 *lnotab++ = 255;
5472 *lnotab++ = 0;
5473 }
5474 d_bytecode -= ncodes * 255;
5475 a->a_lnotab_off += ncodes * 2;
5476 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005477 assert(0 <= d_bytecode && d_bytecode <= 255);
5478
5479 if (d_lineno < -128 || 127 < d_lineno) {
5480 int j, nbytes, ncodes, k;
5481 if (d_lineno < 0) {
5482 k = -128;
5483 /* use division on positive numbers */
5484 ncodes = (-d_lineno) / 128;
5485 }
5486 else {
5487 k = 127;
5488 ncodes = d_lineno / 127;
5489 }
5490 d_lineno -= ncodes * k;
5491 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 nbytes = a->a_lnotab_off + 2 * ncodes;
5493 len = PyBytes_GET_SIZE(a->a_lnotab);
5494 if (nbytes >= len) {
5495 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5496 len = nbytes;
5497 else if (len <= INT_MAX / 2)
5498 len *= 2;
5499 else {
5500 PyErr_NoMemory();
5501 return 0;
5502 }
5503 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5504 return 0;
5505 }
5506 lnotab = (unsigned char *)
5507 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5508 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005509 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 d_bytecode = 0;
5511 for (j = 1; j < ncodes; j++) {
5512 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005513 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 a->a_lnotab_off += ncodes * 2;
5516 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005517 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 len = PyBytes_GET_SIZE(a->a_lnotab);
5520 if (a->a_lnotab_off + 2 >= len) {
5521 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5522 return 0;
5523 }
5524 lnotab = (unsigned char *)
5525 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 a->a_lnotab_off += 2;
5528 if (d_bytecode) {
5529 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005530 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 }
5532 else { /* First line of a block; def stmt, etc. */
5533 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005534 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 }
5536 a->a_lineno = i->i_lineno;
5537 a->a_lineno_off = a->a_offset;
5538 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005539}
5540
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005541/* assemble_emit()
5542 Extend the bytecode with a new instruction.
5543 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005544*/
5545
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005546static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005548{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005549 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005551 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005552
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005553 arg = i->i_oparg;
5554 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 if (i->i_lineno && !assemble_lnotab(a, i))
5556 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005557 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 if (len > PY_SSIZE_T_MAX / 2)
5559 return 0;
5560 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5561 return 0;
5562 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005563 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005565 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005567}
5568
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005569static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005573 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 /* Compute the size of each block and fixup jump args.
5577 Replace block pointer with position in bytecode. */
5578 do {
5579 totsize = 0;
5580 for (i = a->a_nblocks - 1; i >= 0; i--) {
5581 b = a->a_postorder[i];
5582 bsize = blocksize(b);
5583 b->b_offset = totsize;
5584 totsize += bsize;
5585 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005586 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5588 bsize = b->b_offset;
5589 for (i = 0; i < b->b_iused; i++) {
5590 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005591 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 /* Relative jumps are computed relative to
5593 the instruction pointer after fetching
5594 the jump instruction.
5595 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005596 bsize += isize;
5597 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005599 if (instr->i_jrel) {
5600 instr->i_oparg -= bsize;
5601 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005602 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005603 if (instrsize(instr->i_oparg) != isize) {
5604 extended_arg_recompile = 1;
5605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 }
5608 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 /* XXX: This is an awful hack that could hurt performance, but
5611 on the bright side it should work until we come up
5612 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 The issue is that in the first loop blocksize() is called
5615 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005616 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 So we loop until we stop seeing new EXTENDED_ARGs.
5620 The only EXTENDED_ARGs that could be popping up are
5621 ones in jump instructions. So this should converge
5622 fairly quickly.
5623 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005624 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005625}
5626
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005627static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005628dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005631 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 tuple = PyTuple_New(size);
5634 if (tuple == NULL)
5635 return NULL;
5636 while (PyDict_Next(dict, &pos, &k, &v)) {
5637 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005638 Py_INCREF(k);
5639 assert((i - offset) < size);
5640 assert((i - offset) >= 0);
5641 PyTuple_SET_ITEM(tuple, i - offset, k);
5642 }
5643 return tuple;
5644}
5645
5646static PyObject *
5647consts_dict_keys_inorder(PyObject *dict)
5648{
5649 PyObject *consts, *k, *v;
5650 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5651
5652 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5653 if (consts == NULL)
5654 return NULL;
5655 while (PyDict_Next(dict, &pos, &k, &v)) {
5656 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005657 /* The keys of the dictionary can be tuples wrapping a contant.
5658 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5659 * the object we want is always second. */
5660 if (PyTuple_CheckExact(k)) {
5661 k = PyTuple_GET_ITEM(k, 1);
5662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005664 assert(i < size);
5665 assert(i >= 0);
5666 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005668 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005669}
5670
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005671static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005672compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005675 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005677 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 if (ste->ste_nested)
5679 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005680 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005682 if (!ste->ste_generator && ste->ste_coroutine)
5683 flags |= CO_COROUTINE;
5684 if (ste->ste_generator && ste->ste_coroutine)
5685 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 if (ste->ste_varargs)
5687 flags |= CO_VARARGS;
5688 if (ste->ste_varkeywords)
5689 flags |= CO_VARKEYWORDS;
5690 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 /* (Only) inherit compilerflags in PyCF_MASK */
5693 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005696}
5697
INADA Naokic2e16072018-11-26 21:23:22 +09005698// Merge *tuple* with constant cache.
5699// Unlike merge_consts_recursive(), this function doesn't work recursively.
5700static int
5701merge_const_tuple(struct compiler *c, PyObject **tuple)
5702{
5703 assert(PyTuple_CheckExact(*tuple));
5704
5705 PyObject *key = _PyCode_ConstantKey(*tuple);
5706 if (key == NULL) {
5707 return 0;
5708 }
5709
5710 // t is borrowed reference
5711 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5712 Py_DECREF(key);
5713 if (t == NULL) {
5714 return 0;
5715 }
5716 if (t == key) { // tuple is new constant.
5717 return 1;
5718 }
5719
5720 PyObject *u = PyTuple_GET_ITEM(t, 1);
5721 Py_INCREF(u);
5722 Py_DECREF(*tuple);
5723 *tuple = u;
5724 return 1;
5725}
5726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005727static PyCodeObject *
5728makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 PyObject *tmp;
5731 PyCodeObject *co = NULL;
5732 PyObject *consts = NULL;
5733 PyObject *names = NULL;
5734 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 PyObject *name = NULL;
5736 PyObject *freevars = NULL;
5737 PyObject *cellvars = NULL;
5738 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005739 Py_ssize_t nlocals;
5740 int nlocals_int;
5741 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005742 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005743
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005744 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 names = dict_keys_inorder(c->u->u_names, 0);
5746 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5747 if (!consts || !names || !varnames)
5748 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5751 if (!cellvars)
5752 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005753 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 if (!freevars)
5755 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005756
INADA Naokic2e16072018-11-26 21:23:22 +09005757 if (!merge_const_tuple(c, &names) ||
5758 !merge_const_tuple(c, &varnames) ||
5759 !merge_const_tuple(c, &cellvars) ||
5760 !merge_const_tuple(c, &freevars))
5761 {
5762 goto error;
5763 }
5764
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005765 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005766 assert(nlocals < INT_MAX);
5767 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 flags = compute_code_flags(c);
5770 if (flags < 0)
5771 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5774 if (!bytecode)
5775 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5778 if (!tmp)
5779 goto error;
5780 Py_DECREF(consts);
5781 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005782 if (!merge_const_tuple(c, &consts)) {
5783 goto error;
5784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785
Victor Stinnerf8e32212013-11-19 23:56:34 +01005786 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5787 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005788 maxdepth = stackdepth(c);
5789 if (maxdepth < 0) {
5790 goto error;
5791 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005792 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005793 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 bytecode, consts, names, varnames,
5795 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005796 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 c->u->u_firstlineno,
5798 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005799 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 Py_XDECREF(consts);
5801 Py_XDECREF(names);
5802 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 Py_XDECREF(name);
5804 Py_XDECREF(freevars);
5805 Py_XDECREF(cellvars);
5806 Py_XDECREF(bytecode);
5807 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005808}
5809
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005810
5811/* For debugging purposes only */
5812#if 0
5813static void
5814dump_instr(const struct instr *i)
5815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 const char *jrel = i->i_jrel ? "jrel " : "";
5817 const char *jabs = i->i_jabs ? "jabs " : "";
5818 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005821 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5825 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005826}
5827
5828static void
5829dump_basicblock(const basicblock *b)
5830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 const char *seen = b->b_seen ? "seen " : "";
5832 const char *b_return = b->b_return ? "return " : "";
5833 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5834 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5835 if (b->b_instr) {
5836 int i;
5837 for (i = 0; i < b->b_iused; i++) {
5838 fprintf(stderr, " [%02d] ", i);
5839 dump_instr(b->b_instr + i);
5840 }
5841 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005842}
5843#endif
5844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005845static PyCodeObject *
5846assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 basicblock *b, *entryblock;
5849 struct assembler a;
5850 int i, j, nblocks;
5851 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 /* Make sure every block that falls off the end returns None.
5854 XXX NEXT_BLOCK() isn't quite right, because if the last
5855 block ends with a jump or return b_next shouldn't set.
5856 */
5857 if (!c->u->u_curblock->b_return) {
5858 NEXT_BLOCK(c);
5859 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005860 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 ADDOP(c, RETURN_VALUE);
5862 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 nblocks = 0;
5865 entryblock = NULL;
5866 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5867 nblocks++;
5868 entryblock = b;
5869 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 /* Set firstlineno if it wasn't explicitly set. */
5872 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005873 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5875 else
5876 c->u->u_firstlineno = 1;
5877 }
5878 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5879 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005880 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005882 /* Can't modify the bytecode after computing jump offsets. */
5883 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 /* Emit code in reverse postorder from dfs. */
5886 for (i = a.a_nblocks - 1; i >= 0; i--) {
5887 b = a.a_postorder[i];
5888 for (j = 0; j < b->b_iused; j++)
5889 if (!assemble_emit(&a, &b->b_instr[j]))
5890 goto error;
5891 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5894 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005895 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005899 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 assemble_free(&a);
5901 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005902}
Georg Brandl8334fd92010-12-04 10:26:46 +00005903
5904#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005905PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005906PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5907 PyArena *arena)
5908{
5909 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5910}