blob: 9713bfc9e9b737306b48c94ac2607980f8528d8c [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 Storchakad31e7732018-10-21 10:09:39 +0300178static int compiler_warn(struct compiler *, const char *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
180
181static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
182static int compiler_visit_stmt(struct compiler *, stmt_ty);
183static int compiler_visit_keyword(struct compiler *, keyword_ty);
184static int compiler_visit_expr(struct compiler *, expr_ty);
185static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700186static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200191static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500193static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400194static int compiler_async_with(struct compiler *, stmt_ty, int);
195static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100196static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400198 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500199static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400200static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000201
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700202static int compiler_sync_comprehension_generator(
203 struct compiler *c,
204 asdl_seq *generators, int gen_index,
205 expr_ty elt, expr_ty val, int type);
206
207static int compiler_async_comprehension_generator(
208 struct compiler *c,
209 asdl_seq *generators, int gen_index,
210 expr_ty elt, expr_ty val, int type);
211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000213static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400215#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Name mangling: __private becomes _classname__private.
221 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200222 PyObject *result;
223 size_t nlen, plen, ipriv;
224 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200226 PyUnicode_READ_CHAR(ident, 0) != '_' ||
227 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_INCREF(ident);
229 return ident;
230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200231 nlen = PyUnicode_GET_LENGTH(ident);
232 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 The only time a name with a dot can occur is when
236 we are compiling an import statement that has a
237 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 TODO(jhylton): Decide whether we want to support
240 mangling of the module name, e.g. __M.X.
241 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
243 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
244 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle __whatever__ */
247 }
248 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 ipriv = 0;
250 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
251 ipriv++;
252 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_INCREF(ident);
254 return ident; /* Don't mangle if class is just underscores */
255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Antoine Pitrou55bff892013-04-06 21:21:04 +0200258 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
259 PyErr_SetString(PyExc_OverflowError,
260 "private identifier too large to be mangled");
261 return NULL;
262 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
265 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
266 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
267
268 result = PyUnicode_New(1 + nlen + plen, maxchar);
269 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
272 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200273 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
274 Py_DECREF(result);
275 return NULL;
276 }
277 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
278 Py_DECREF(result);
279 return NULL;
280 }
Victor Stinner8f825062012-04-27 13:55:39 +0200281 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000283}
284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285static int
286compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000289
INADA Naokic2e16072018-11-26 21:23:22 +0900290 c->c_const_cache = PyDict_New();
291 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900293 }
294
295 c->c_stack = PyList_New(0);
296 if (!c->c_stack) {
297 Py_CLEAR(c->c_const_cache);
298 return 0;
299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302}
303
304PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200305PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
306 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 struct compiler c;
309 PyCodeObject *co = NULL;
310 PyCompilerFlags local_flags;
311 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!__doc__) {
314 __doc__ = PyUnicode_InternFromString("__doc__");
315 if (!__doc__)
316 return NULL;
317 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000318 if (!__annotations__) {
319 __annotations__ = PyUnicode_InternFromString("__annotations__");
320 if (!__annotations__)
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!compiler_init(&c))
324 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 c.c_filename = filename;
327 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200328 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (c.c_future == NULL)
330 goto finally;
331 if (!flags) {
332 local_flags.cf_flags = 0;
333 flags = &local_flags;
334 }
335 merged = c.c_future->ff_features | flags->cf_flags;
336 c.c_future->ff_features = merged;
337 flags->cf_flags = merged;
338 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000339 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200342 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900343 goto finally;
344 }
345
Victor Stinner14e461d2013-08-26 22:28:21 +0200346 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (c.c_st == NULL) {
348 if (!PyErr_Occurred())
349 PyErr_SetString(PyExc_SystemError, "no symtable");
350 goto finally;
351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Thomas Wouters1175c432006-02-27 22:49:54 +0000355 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 compiler_free(&c);
357 assert(co || PyErr_Occurred());
358 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359}
360
361PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200362PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
363 int optimize, PyArena *arena)
364{
365 PyObject *filename;
366 PyCodeObject *co;
367 filename = PyUnicode_DecodeFSDefault(filename_str);
368 if (filename == NULL)
369 return NULL;
370 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
371 Py_DECREF(filename);
372 return co;
373
374}
375
376PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377PyNode_Compile(struct _node *n, const char *filename)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyCodeObject *co = NULL;
380 mod_ty mod;
381 PyArena *arena = PyArena_New();
382 if (!arena)
383 return NULL;
384 mod = PyAST_FromNode(n, NULL, filename, arena);
385 if (mod)
386 co = PyAST_Compile(mod, filename, NULL, arena);
387 PyArena_Free(arena);
388 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000389}
390
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (c->c_st)
395 PySymtable_Free(c->c_st);
396 if (c->c_future)
397 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200398 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900399 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401}
402
Guido van Rossum79f25d91997-04-29 20:08:16 +0000403static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 Py_ssize_t i, n;
407 PyObject *v, *k;
408 PyObject *dict = PyDict_New();
409 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 n = PyList_Size(list);
412 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100413 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (!v) {
415 Py_DECREF(dict);
416 return NULL;
417 }
418 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300419 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_DECREF(v);
421 Py_DECREF(dict);
422 return NULL;
423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_DECREF(v);
425 }
426 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427}
428
429/* Return new dict containing names from src that match scope(s).
430
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000431src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433values are integers, starting at offset and increasing by one for
434each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435*/
436
437static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100438dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700440 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500442 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(offset >= 0);
445 if (dest == NULL)
446 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Meador Inge2ca63152012-07-18 14:20:11 -0500448 /* Sort the keys so that we have a deterministic order on the indexes
449 saved in the returned dictionary. These indexes are used as indexes
450 into the free and cell var storage. Therefore if they aren't
451 deterministic, then the generated bytecode is not deterministic.
452 */
453 sorted_keys = PyDict_Keys(src);
454 if (sorted_keys == NULL)
455 return NULL;
456 if (PyList_Sort(sorted_keys) != 0) {
457 Py_DECREF(sorted_keys);
458 return NULL;
459 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500460 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500461
462 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* XXX this should probably be a macro in symtable.h */
464 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500465 k = PyList_GET_ITEM(sorted_keys, key_i);
466 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 assert(PyLong_Check(v));
468 vi = PyLong_AS_LONG(v);
469 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300472 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500474 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_DECREF(dest);
476 return NULL;
477 }
478 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300479 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500480 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_DECREF(item);
482 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
484 }
485 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 }
487 }
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000490}
491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492static void
493compiler_unit_check(struct compiler_unit *u)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 basicblock *block;
496 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700497 assert((uintptr_t)block != 0xcbcbcbcbU);
498 assert((uintptr_t)block != 0xfbfbfbfbU);
499 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (block->b_instr != NULL) {
501 assert(block->b_ialloc > 0);
502 assert(block->b_iused > 0);
503 assert(block->b_ialloc >= block->b_iused);
504 }
505 else {
506 assert (block->b_iused == 0);
507 assert (block->b_ialloc == 0);
508 }
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510}
511
512static void
513compiler_unit_free(struct compiler_unit *u)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 compiler_unit_check(u);
518 b = u->u_blocks;
519 while (b != NULL) {
520 if (b->b_instr)
521 PyObject_Free((void *)b->b_instr);
522 next = b->b_list;
523 PyObject_Free((void *)b);
524 b = next;
525 }
526 Py_CLEAR(u->u_ste);
527 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400528 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 Py_CLEAR(u->u_consts);
530 Py_CLEAR(u->u_names);
531 Py_CLEAR(u->u_varnames);
532 Py_CLEAR(u->u_freevars);
533 Py_CLEAR(u->u_cellvars);
534 Py_CLEAR(u->u_private);
535 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100539compiler_enter_scope(struct compiler *c, identifier name,
540 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100543 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
546 struct compiler_unit));
547 if (!u) {
548 PyErr_NoMemory();
549 return 0;
550 }
551 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100552 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u->u_argcount = 0;
554 u->u_kwonlyargcount = 0;
555 u->u_ste = PySymtable_Lookup(c->c_st, key);
556 if (!u->u_ste) {
557 compiler_unit_free(u);
558 return 0;
559 }
560 Py_INCREF(name);
561 u->u_name = name;
562 u->u_varnames = list2dict(u->u_ste->ste_varnames);
563 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
564 if (!u->u_varnames || !u->u_cellvars) {
565 compiler_unit_free(u);
566 return 0;
567 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000569 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500570 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300571 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 int res;
573 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200574 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 name = _PyUnicode_FromId(&PyId___class__);
576 if (!name) {
577 compiler_unit_free(u);
578 return 0;
579 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 if (res < 0) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200588 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!u->u_freevars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_blocks = NULL;
595 u->u_nfblocks = 0;
596 u->u_firstlineno = lineno;
597 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000598 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_lineno_set = 0;
600 u->u_consts = PyDict_New();
601 if (!u->u_consts) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 u->u_names = PyDict_New();
606 if (!u->u_names) {
607 compiler_unit_free(u);
608 return 0;
609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Push the old compiler_unit on the stack. */
614 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400615 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
617 Py_XDECREF(capsule);
618 compiler_unit_free(u);
619 return 0;
620 }
621 Py_DECREF(capsule);
622 u->u_private = c->u->u_private;
623 Py_XINCREF(u->u_private);
624 }
625 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100628
629 block = compiler_new_block(c);
630 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100632 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400634 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
635 if (!compiler_set_qualname(c))
636 return 0;
637 }
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640}
641
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643compiler_exit_scope(struct compiler *c)
644{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100645 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 c->c_nestlevel--;
649 compiler_unit_free(c->u);
650 /* Restore c->u to the parent unit. */
651 n = PyList_GET_SIZE(c->c_stack) - 1;
652 if (n >= 0) {
653 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400654 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 assert(c->u);
656 /* we are deleting from a list so this really shouldn't fail */
657 if (PySequence_DelItem(c->c_stack, n) < 0)
658 Py_FatalError("compiler_exit_scope()");
659 compiler_unit_check(c->u);
660 }
661 else
662 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666static int
667compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 _Py_static_string(dot_locals, ".<locals>");
671 Py_ssize_t stack_size;
672 struct compiler_unit *u = c->u;
673 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400677 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 if (stack_size > 1) {
679 int scope, force_global = 0;
680 struct compiler_unit *parent;
681 PyObject *mangled, *capsule;
682
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400683 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(parent);
686
Yury Selivanov75445082015-05-11 22:57:16 -0400687 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 assert(u->u_name);
691 mangled = _Py_Mangle(parent->u_private, u->u_name);
692 if (!mangled)
693 return 0;
694 scope = PyST_GetScope(parent->u_ste, mangled);
695 Py_DECREF(mangled);
696 assert(scope != GLOBAL_IMPLICIT);
697 if (scope == GLOBAL_EXPLICIT)
698 force_global = 1;
699 }
700
701 if (!force_global) {
702 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400703 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
705 dot_locals_str = _PyUnicode_FromId(&dot_locals);
706 if (dot_locals_str == NULL)
707 return 0;
708 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
709 if (base == NULL)
710 return 0;
711 }
712 else {
713 Py_INCREF(parent->u_qualname);
714 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400715 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100716 }
717 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 if (base != NULL) {
720 dot_str = _PyUnicode_FromId(&dot);
721 if (dot_str == NULL) {
722 Py_DECREF(base);
723 return 0;
724 }
725 name = PyUnicode_Concat(base, dot_str);
726 Py_DECREF(base);
727 if (name == NULL)
728 return 0;
729 PyUnicode_Append(&name, u->u_name);
730 if (name == NULL)
731 return 0;
732 }
733 else {
734 Py_INCREF(u->u_name);
735 name = u->u_name;
736 }
737 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100738
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400739 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740}
741
Eric V. Smith235a6f02015-09-19 14:51:32 -0400742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743/* Allocate a new block and return a pointer to it.
744 Returns NULL on error.
745*/
746
747static basicblock *
748compiler_new_block(struct compiler *c)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 basicblock *b;
751 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 u = c->u;
754 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
755 if (b == NULL) {
756 PyErr_NoMemory();
757 return NULL;
758 }
759 memset((void *)b, 0, sizeof(basicblock));
760 /* Extend the singly linked list of blocks with new block. */
761 b->b_list = u->u_blocks;
762 u->u_blocks = b;
763 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764}
765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767compiler_next_block(struct compiler *c)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 basicblock *block = compiler_new_block(c);
770 if (block == NULL)
771 return NULL;
772 c->u->u_curblock->b_next = block;
773 c->u->u_curblock = block;
774 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
777static basicblock *
778compiler_use_next_block(struct compiler *c, basicblock *block)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 assert(block != NULL);
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786/* Returns the offset of the next instruction in the current block's
787 b_instr array. Resizes the b_instr as necessary.
788 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790
791static int
792compiler_next_instr(struct compiler *c, basicblock *b)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(b != NULL);
795 if (b->b_instr == NULL) {
796 b->b_instr = (struct instr *)PyObject_Malloc(
797 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
798 if (b->b_instr == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 b->b_ialloc = DEFAULT_BLOCK_SIZE;
803 memset((char *)b->b_instr, 0,
804 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
805 }
806 else if (b->b_iused == b->b_ialloc) {
807 struct instr *tmp;
808 size_t oldsize, newsize;
809 oldsize = b->b_ialloc * sizeof(struct instr);
810 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700812 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyErr_NoMemory();
814 return -1;
815 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (newsize == 0) {
818 PyErr_NoMemory();
819 return -1;
820 }
821 b->b_ialloc <<= 1;
822 tmp = (struct instr *)PyObject_Realloc(
823 (void *)b->b_instr, newsize);
824 if (tmp == NULL) {
825 PyErr_NoMemory();
826 return -1;
827 }
828 b->b_instr = tmp;
829 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
830 }
831 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832}
833
Christian Heimes2202f872008-02-06 14:31:34 +0000834/* Set the i_lineno member of the instruction at offset off if the
835 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836 already been set. If it has been set, the call has no effect.
837
Christian Heimes2202f872008-02-06 14:31:34 +0000838 The line number is reset in the following cases:
839 - when entering a new scope
840 - on each statement
841 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200842 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000843 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846static void
847compiler_set_lineno(struct compiler *c, int off)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 basicblock *b;
850 if (c->u->u_lineno_set)
851 return;
852 c->u->u_lineno_set = 1;
853 b = c->u->u_curblock;
854 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855}
856
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200857/* Return the stack effect of opcode with argument oparg.
858
859 Some opcodes have different stack effect when jump to the target and
860 when not jump. The 'jump' parameter specifies the case:
861
862 * 0 -- when not jump
863 * 1 -- when jump
864 * -1 -- maximal
865 */
866/* XXX Make the stack effect of WITH_CLEANUP_START and
867 WITH_CLEANUP_FINISH deterministic. */
868static int
869stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300872 case NOP:
873 case EXTENDED_ARG:
874 return 0;
875
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200876 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case POP_TOP:
878 return -1;
879 case ROT_TWO:
880 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200881 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return 0;
883 case DUP_TOP:
884 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000885 case DUP_TOP_TWO:
886 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case UNARY_POSITIVE:
890 case UNARY_NEGATIVE:
891 case UNARY_NOT:
892 case UNARY_INVERT:
893 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case SET_ADD:
896 case LIST_APPEND:
897 return -1;
898 case MAP_ADD:
899 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000900
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case BINARY_POWER:
903 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400904 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case BINARY_MODULO:
906 case BINARY_ADD:
907 case BINARY_SUBTRACT:
908 case BINARY_SUBSCR:
909 case BINARY_FLOOR_DIVIDE:
910 case BINARY_TRUE_DIVIDE:
911 return -1;
912 case INPLACE_FLOOR_DIVIDE:
913 case INPLACE_TRUE_DIVIDE:
914 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case INPLACE_ADD:
917 case INPLACE_SUBTRACT:
918 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400919 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case INPLACE_MODULO:
921 return -1;
922 case STORE_SUBSCR:
923 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case DELETE_SUBSCR:
925 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case BINARY_LSHIFT:
928 case BINARY_RSHIFT:
929 case BINARY_AND:
930 case BINARY_XOR:
931 case BINARY_OR:
932 return -1;
933 case INPLACE_POWER:
934 return -1;
935 case GET_ITER:
936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case PRINT_EXPR:
939 return -1;
940 case LOAD_BUILD_CLASS:
941 return 1;
942 case INPLACE_LSHIFT:
943 case INPLACE_RSHIFT:
944 case INPLACE_AND:
945 case INPLACE_XOR:
946 case INPLACE_OR:
947 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200950 /* 1 in the normal flow.
951 * Restore the stack position and push 6 values before jumping to
952 * the handler if an exception be raised. */
953 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400954 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400956 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200957 /* Pop a variable number of values pushed by WITH_CLEANUP_START
958 * + __exit__ or __aexit__. */
959 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case RETURN_VALUE:
961 return -1;
962 case IMPORT_STAR:
963 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700964 case SETUP_ANNOTATIONS:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case YIELD_VALUE:
967 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500968 case YIELD_FROM:
969 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case POP_BLOCK:
971 return 0;
972 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200973 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200975 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 /* Pop 6 values when an exception was raised. */
977 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case STORE_NAME:
980 return -1;
981 case DELETE_NAME:
982 return 0;
983 case UNPACK_SEQUENCE:
984 return oparg-1;
985 case UNPACK_EX:
986 return (oparg&0xFF) + (oparg>>8);
987 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200988 /* -1 at end of iterator, 1 if continue iterating. */
989 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 case STORE_ATTR:
992 return -2;
993 case DELETE_ATTR:
994 return -1;
995 case STORE_GLOBAL:
996 return -1;
997 case DELETE_GLOBAL:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_CONST:
1000 return 1;
1001 case LOAD_NAME:
1002 return 1;
1003 case BUILD_TUPLE:
1004 case BUILD_LIST:
1005 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001006 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001008 case BUILD_LIST_UNPACK:
1009 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001010 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_SET_UNPACK:
1012 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001014 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001016 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001017 case BUILD_CONST_KEY_MAP:
1018 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case LOAD_ATTR:
1020 return 0;
1021 case COMPARE_OP:
1022 return -1;
1023 case IMPORT_NAME:
1024 return -1;
1025 case IMPORT_FROM:
1026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001028 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_ABSOLUTE:
1031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 case JUMP_IF_TRUE_OR_POP:
1034 case JUMP_IF_FALSE_OR_POP:
1035 return jump ? 0 : -1;
1036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case POP_JUMP_IF_FALSE:
1038 case POP_JUMP_IF_TRUE:
1039 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_GLOBAL:
1042 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001044 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001046 /* 0 in the normal flow.
1047 * Restore the stack position and push 6 values before jumping to
1048 * the handler if an exception be raised. */
1049 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001050 case BEGIN_FINALLY:
1051 /* Actually pushes 1 value, but count 6 for balancing with
1052 * END_FINALLY and POP_FINALLY.
1053 * This is the main reason of using this opcode instead of
1054 * "LOAD_CONST None". */
1055 return 6;
1056 case CALL_FINALLY:
1057 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case LOAD_FAST:
1060 return 1;
1061 case STORE_FAST:
1062 return -1;
1063 case DELETE_FAST:
1064 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 case RAISE_VARARGS:
1067 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001068
1069 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001071 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001072 case CALL_METHOD:
1073 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001075 return -oparg-1;
1076 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001077 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001078 case MAKE_FUNCTION:
1079 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1080 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 case BUILD_SLICE:
1082 if (oparg == 3)
1083 return -2;
1084 else
1085 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001087 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 case LOAD_CLOSURE:
1089 return 1;
1090 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001091 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return 1;
1093 case STORE_DEREF:
1094 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001095 case DELETE_DEREF:
1096 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001097
1098 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001099 case GET_AWAITABLE:
1100 return 0;
1101 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001102 /* 0 in the normal flow.
1103 * Restore the stack position to the position before the result
1104 * of __aenter__ and push 6 values before jumping to the handler
1105 * if an exception be raised. */
1106 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001107 case BEFORE_ASYNC_WITH:
1108 return 1;
1109 case GET_AITER:
1110 return 0;
1111 case GET_ANEXT:
1112 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001113 case GET_YIELD_FROM_ITER:
1114 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001115 case END_ASYNC_FOR:
1116 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001117 case FORMAT_VALUE:
1118 /* If there's a fmt_spec on the stack, we go from 2->1,
1119 else 1->1. */
1120 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001121 case LOAD_METHOD:
1122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001124 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
Larry Hastings3a907972013-11-23 14:49:22 -08001126 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127}
1128
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001129int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001130PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1131{
1132 return stack_effect(opcode, oparg, jump);
1133}
1134
1135int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001136PyCompile_OpcodeStackEffect(int opcode, int oparg)
1137{
1138 return stack_effect(opcode, oparg, -1);
1139}
1140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141/* Add an opcode with no argument.
1142 Returns 0 on failure, 1 on success.
1143*/
1144
1145static int
1146compiler_addop(struct compiler *c, int opcode)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 basicblock *b;
1149 struct instr *i;
1150 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001151 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 off = compiler_next_instr(c, c->u->u_curblock);
1153 if (off < 0)
1154 return 0;
1155 b = c->u->u_curblock;
1156 i = &b->b_instr[off];
1157 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001158 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (opcode == RETURN_VALUE)
1160 b->b_return = 1;
1161 compiler_set_lineno(c, off);
1162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163}
1164
Victor Stinnerf8e32212013-11-19 23:56:34 +01001165static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1167{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001168 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001173 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001175 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001176 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return -1;
1180 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_DECREF(v);
1183 return -1;
1184 }
1185 Py_DECREF(v);
1186 }
1187 else
1188 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001189 return arg;
1190}
1191
INADA Naokic2e16072018-11-26 21:23:22 +09001192// Merge const *o* recursively and return constant key object.
1193static PyObject*
1194merge_consts_recursive(struct compiler *c, PyObject *o)
1195{
1196 // None and Ellipsis are singleton, and key is the singleton.
1197 // No need to merge object and key.
1198 if (o == Py_None || o == Py_Ellipsis) {
1199 Py_INCREF(o);
1200 return o;
1201 }
1202
1203 PyObject *key = _PyCode_ConstantKey(o);
1204 if (key == NULL) {
1205 return NULL;
1206 }
1207
1208 // t is borrowed reference
1209 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1210 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001211 // o is registered in c_const_cache. Just use it.
INADA Naokic2e16072018-11-26 21:23:22 +09001212 Py_INCREF(t);
1213 Py_DECREF(key);
1214 return t;
1215 }
1216
INADA Naokif7e4d362018-11-29 00:58:46 +09001217 // We registered o in c_const_cache.
1218 // When o is a tuple or frozenset, we want to merge it's
1219 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001220 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 Py_ssize_t len = PyTuple_GET_SIZE(o);
1222 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001223 PyObject *item = PyTuple_GET_ITEM(o, i);
1224 PyObject *u = merge_consts_recursive(c, item);
1225 if (u == NULL) {
1226 Py_DECREF(key);
1227 return NULL;
1228 }
1229
1230 // See _PyCode_ConstantKey()
1231 PyObject *v; // borrowed
1232 if (PyTuple_CheckExact(u)) {
1233 v = PyTuple_GET_ITEM(u, 1);
1234 }
1235 else {
1236 v = u;
1237 }
1238 if (v != item) {
1239 Py_INCREF(v);
1240 PyTuple_SET_ITEM(o, i, v);
1241 Py_DECREF(item);
1242 }
1243
1244 Py_DECREF(u);
1245 }
1246 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001247 else if (PyFrozenSet_CheckExact(o)) {
1248 // *key* is tuple. And it's first item is frozenset of
1249 // constant keys.
1250 // See _PyCode_ConstantKey() for detail.
1251 assert(PyTuple_CheckExact(key));
1252 assert(PyTuple_GET_SIZE(key) == 2);
1253
1254 Py_ssize_t len = PySet_GET_SIZE(o);
1255 if (len == 0) { // empty frozenset should not be re-created.
1256 return key;
1257 }
1258 PyObject *tuple = PyTuple_New(len);
1259 if (tuple == NULL) {
1260 Py_DECREF(key);
1261 return NULL;
1262 }
1263 Py_ssize_t i = 0, pos = 0;
1264 PyObject *item;
1265 Py_hash_t hash;
1266 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1267 PyObject *k = merge_consts_recursive(c, item);
1268 if (k == NULL) {
1269 Py_DECREF(tuple);
1270 Py_DECREF(key);
1271 return NULL;
1272 }
1273 PyObject *u;
1274 if (PyTuple_CheckExact(k)) {
1275 u = PyTuple_GET_ITEM(k, 1);
1276 Py_INCREF(u);
1277 Py_DECREF(k);
1278 }
1279 else {
1280 u = k;
1281 }
1282 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1283 i++;
1284 }
1285
1286 // Instead of rewriting o, we create new frozenset and embed in the
1287 // key tuple. Caller should get merged frozenset from the key tuple.
1288 PyObject *new = PyFrozenSet_New(tuple);
1289 Py_DECREF(tuple);
1290 if (new == NULL) {
1291 Py_DECREF(key);
1292 return NULL;
1293 }
1294 assert(PyTuple_GET_ITEM(key, 1) == o);
1295 Py_DECREF(o);
1296 PyTuple_SET_ITEM(key, 1, new);
1297 }
INADA Naokic2e16072018-11-26 21:23:22 +09001298
1299 return key;
1300}
1301
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001302static Py_ssize_t
1303compiler_add_const(struct compiler *c, PyObject *o)
1304{
INADA Naokic2e16072018-11-26 21:23:22 +09001305 PyObject *key = merge_consts_recursive(c, o);
1306 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001308 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001309
INADA Naokic2e16072018-11-26 21:23:22 +09001310 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1311 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
1315static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316compiler_addop_load_const(struct compiler *c, PyObject *o)
1317{
1318 Py_ssize_t arg = compiler_add_const(c, o);
1319 if (arg < 0)
1320 return 0;
1321 return compiler_addop_i(c, LOAD_CONST, arg);
1322}
1323
1324static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001328 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 return compiler_addop_i(c, opcode, arg);
1332}
1333
1334static int
1335compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001338 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1340 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 arg = compiler_add_o(c, dict, mangled);
1343 Py_DECREF(mangled);
1344 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 return compiler_addop_i(c, opcode, arg);
1347}
1348
1349/* Add an opcode with an integer argument.
1350 Returns 0 on failure, 1 on success.
1351*/
1352
1353static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001354compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 struct instr *i;
1357 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358
Victor Stinner2ad474b2016-03-01 23:34:47 +01001359 /* oparg value is unsigned, but a signed C int is usually used to store
1360 it in the C code (like Python/ceval.c).
1361
1362 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1363
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001364 The argument of a concrete bytecode instruction is limited to 8-bit.
1365 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1366 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001367 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 off = compiler_next_instr(c, c->u->u_curblock);
1370 if (off < 0)
1371 return 0;
1372 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001373 i->i_opcode = opcode;
1374 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 compiler_set_lineno(c, off);
1376 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377}
1378
1379static int
1380compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 struct instr *i;
1383 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001385 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 assert(b != NULL);
1387 off = compiler_next_instr(c, c->u->u_curblock);
1388 if (off < 0)
1389 return 0;
1390 i = &c->u->u_curblock->b_instr[off];
1391 i->i_opcode = opcode;
1392 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (absolute)
1394 i->i_jabs = 1;
1395 else
1396 i->i_jrel = 1;
1397 compiler_set_lineno(c, off);
1398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399}
1400
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001401/* NEXT_BLOCK() creates an implicit jump from the current block
1402 to the new block.
1403
1404 The returns inside this macro make it impossible to decref objects
1405 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (compiler_next_block((C)) == NULL) \
1409 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
1412#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!compiler_addop((C), (OP))) \
1414 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415}
1416
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001417#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!compiler_addop((C), (OP))) { \
1419 compiler_exit_scope(c); \
1420 return 0; \
1421 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001422}
1423
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001424#define ADDOP_LOAD_CONST(C, O) { \
1425 if (!compiler_addop_load_const((C), (O))) \
1426 return 0; \
1427}
1428
1429/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1430#define ADDOP_LOAD_CONST_NEW(C, O) { \
1431 PyObject *__new_const = (O); \
1432 if (__new_const == NULL) { \
1433 return 0; \
1434 } \
1435 if (!compiler_addop_load_const((C), __new_const)) { \
1436 Py_DECREF(__new_const); \
1437 return 0; \
1438 } \
1439 Py_DECREF(__new_const); \
1440}
1441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1444 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001447/* Same as ADDOP_O, but steals a reference. */
1448#define ADDOP_N(C, OP, O, TYPE) { \
1449 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1450 Py_DECREF((O)); \
1451 return 0; \
1452 } \
1453 Py_DECREF((O)); \
1454}
1455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1458 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459}
1460
1461#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_addop_i((C), (OP), (O))) \
1463 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_j((C), (OP), (O), 1)) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_j((C), (OP), (O), 0)) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
1476/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1477 the ASDL name to synthesize the name of the C type and the visit function.
1478*/
1479
1480#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_visit_ ## TYPE((C), (V))) \
1482 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483}
1484
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001485#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_visit_ ## TYPE((C), (V))) { \
1487 compiler_exit_scope(c); \
1488 return 0; \
1489 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001490}
1491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!compiler_visit_slice((C), (V), (CTX))) \
1494 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495}
1496
1497#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 int _i; \
1499 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1500 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1501 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1502 if (!compiler_visit_ ## TYPE((C), elt)) \
1503 return 0; \
1504 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001507#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 int _i; \
1509 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1510 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1511 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1512 if (!compiler_visit_ ## TYPE((C), elt)) { \
1513 compiler_exit_scope(c); \
1514 return 0; \
1515 } \
1516 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001517}
1518
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001519/* Search if variable annotations are present statically in a block. */
1520
1521static int
1522find_ann(asdl_seq *stmts)
1523{
1524 int i, j, res = 0;
1525 stmt_ty st;
1526
1527 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1528 st = (stmt_ty)asdl_seq_GET(stmts, i);
1529 switch (st->kind) {
1530 case AnnAssign_kind:
1531 return 1;
1532 case For_kind:
1533 res = find_ann(st->v.For.body) ||
1534 find_ann(st->v.For.orelse);
1535 break;
1536 case AsyncFor_kind:
1537 res = find_ann(st->v.AsyncFor.body) ||
1538 find_ann(st->v.AsyncFor.orelse);
1539 break;
1540 case While_kind:
1541 res = find_ann(st->v.While.body) ||
1542 find_ann(st->v.While.orelse);
1543 break;
1544 case If_kind:
1545 res = find_ann(st->v.If.body) ||
1546 find_ann(st->v.If.orelse);
1547 break;
1548 case With_kind:
1549 res = find_ann(st->v.With.body);
1550 break;
1551 case AsyncWith_kind:
1552 res = find_ann(st->v.AsyncWith.body);
1553 break;
1554 case Try_kind:
1555 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1556 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1557 st->v.Try.handlers, j);
1558 if (find_ann(handler->v.ExceptHandler.body)) {
1559 return 1;
1560 }
1561 }
1562 res = find_ann(st->v.Try.body) ||
1563 find_ann(st->v.Try.finalbody) ||
1564 find_ann(st->v.Try.orelse);
1565 break;
1566 default:
1567 res = 0;
1568 }
1569 if (res) {
1570 break;
1571 }
1572 }
1573 return res;
1574}
1575
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001576/*
1577 * Frame block handling functions
1578 */
1579
1580static int
1581compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1582 basicblock *exit)
1583{
1584 struct fblockinfo *f;
1585 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1586 PyErr_SetString(PyExc_SyntaxError,
1587 "too many statically nested blocks");
1588 return 0;
1589 }
1590 f = &c->u->u_fblock[c->u->u_nfblocks++];
1591 f->fb_type = t;
1592 f->fb_block = b;
1593 f->fb_exit = exit;
1594 return 1;
1595}
1596
1597static void
1598compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1599{
1600 struct compiler_unit *u = c->u;
1601 assert(u->u_nfblocks > 0);
1602 u->u_nfblocks--;
1603 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1604 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1605}
1606
1607/* Unwind a frame block. If preserve_tos is true, the TOS before
1608 * popping the blocks will be restored afterwards.
1609 */
1610static int
1611compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1612 int preserve_tos)
1613{
1614 switch (info->fb_type) {
1615 case WHILE_LOOP:
1616 return 1;
1617
1618 case FINALLY_END:
1619 ADDOP_I(c, POP_FINALLY, preserve_tos);
1620 return 1;
1621
1622 case FOR_LOOP:
1623 /* Pop the iterator */
1624 if (preserve_tos) {
1625 ADDOP(c, ROT_TWO);
1626 }
1627 ADDOP(c, POP_TOP);
1628 return 1;
1629
1630 case EXCEPT:
1631 ADDOP(c, POP_BLOCK);
1632 return 1;
1633
1634 case FINALLY_TRY:
1635 ADDOP(c, POP_BLOCK);
1636 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1637 return 1;
1638
1639 case WITH:
1640 case ASYNC_WITH:
1641 ADDOP(c, POP_BLOCK);
1642 if (preserve_tos) {
1643 ADDOP(c, ROT_TWO);
1644 }
1645 ADDOP(c, BEGIN_FINALLY);
1646 ADDOP(c, WITH_CLEANUP_START);
1647 if (info->fb_type == ASYNC_WITH) {
1648 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001649 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001650 ADDOP(c, YIELD_FROM);
1651 }
1652 ADDOP(c, WITH_CLEANUP_FINISH);
1653 ADDOP_I(c, POP_FINALLY, 0);
1654 return 1;
1655
1656 case HANDLER_CLEANUP:
1657 if (preserve_tos) {
1658 ADDOP(c, ROT_FOUR);
1659 }
1660 if (info->fb_exit) {
1661 ADDOP(c, POP_BLOCK);
1662 ADDOP(c, POP_EXCEPT);
1663 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1664 }
1665 else {
1666 ADDOP(c, POP_EXCEPT);
1667 }
1668 return 1;
1669 }
1670 Py_UNREACHABLE();
1671}
1672
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001673/* Compile a sequence of statements, checking for a docstring
1674 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
1676static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001677compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001679 int i = 0;
1680 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001681 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001682
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001683 /* Set current line number to the line number of first statement.
1684 This way line number for SETUP_ANNOTATIONS will always
1685 coincide with the line number of first "real" statement in module.
1686 If body is empy, then lineno will be set later in assemble. */
1687 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1688 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001689 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001690 c->u->u_lineno = st->lineno;
1691 }
1692 /* Every annotated class and module should have __annotations__. */
1693 if (find_ann(stmts)) {
1694 ADDOP(c, SETUP_ANNOTATIONS);
1695 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001696 if (!asdl_seq_LEN(stmts))
1697 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001698 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001699 if (c->c_optimize < 2) {
1700 docstring = _PyAST_GetDocString(stmts);
1701 if (docstring) {
1702 i = 1;
1703 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1704 assert(st->kind == Expr_kind);
1705 VISIT(c, expr, st->v.Expr.value);
1706 if (!compiler_nameop(c, __doc__, Store))
1707 return 0;
1708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001710 for (; i < asdl_seq_LEN(stmts); i++)
1711 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713}
1714
1715static PyCodeObject *
1716compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyCodeObject *co;
1719 int addNone = 1;
1720 static PyObject *module;
1721 if (!module) {
1722 module = PyUnicode_InternFromString("<module>");
1723 if (!module)
1724 return NULL;
1725 }
1726 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001727 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return NULL;
1729 switch (mod->kind) {
1730 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001731 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 compiler_exit_scope(c);
1733 return 0;
1734 }
1735 break;
1736 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001737 if (find_ann(mod->v.Interactive.body)) {
1738 ADDOP(c, SETUP_ANNOTATIONS);
1739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 c->c_interactive = 1;
1741 VISIT_SEQ_IN_SCOPE(c, stmt,
1742 mod->v.Interactive.body);
1743 break;
1744 case Expression_kind:
1745 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1746 addNone = 0;
1747 break;
1748 case Suite_kind:
1749 PyErr_SetString(PyExc_SystemError,
1750 "suite should not be possible");
1751 return 0;
1752 default:
1753 PyErr_Format(PyExc_SystemError,
1754 "module kind %d should not be possible",
1755 mod->kind);
1756 return 0;
1757 }
1758 co = assemble(c, addNone);
1759 compiler_exit_scope(c);
1760 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001761}
1762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763/* The test for LOCAL must come before the test for FREE in order to
1764 handle classes where name is both local and free. The local var is
1765 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001766*/
1767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768static int
1769get_ref_type(struct compiler *c, PyObject *name)
1770{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001771 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001772 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001773 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001774 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001775 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (scope == 0) {
1777 char buf[350];
1778 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001779 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001781 PyUnicode_AsUTF8(name),
1782 PyUnicode_AsUTF8(c->u->u_name),
1783 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1784 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1785 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 );
1788 Py_FatalError(buf);
1789 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792}
1793
1794static int
1795compiler_lookup_arg(PyObject *dict, PyObject *name)
1796{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001797 PyObject *v;
1798 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001800 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001801 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802}
1803
1804static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001805compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001807 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001808 if (qualname == NULL)
1809 qualname = co->co_name;
1810
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 if (free) {
1812 for (i = 0; i < free; ++i) {
1813 /* Bypass com_addop_varname because it will generate
1814 LOAD_DEREF but LOAD_CLOSURE is needed.
1815 */
1816 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1817 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001819 /* Special case: If a class contains a method with a
1820 free variable that has the same name as a method,
1821 the name will be considered free *and* local in the
1822 class. It should be handled by the closure, as
1823 well as by the normal name loookup logic.
1824 */
1825 reftype = get_ref_type(c, name);
1826 if (reftype == CELL)
1827 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1828 else /* (reftype == FREE) */
1829 arg = compiler_lookup_arg(c->u->u_freevars, name);
1830 if (arg == -1) {
1831 fprintf(stderr,
1832 "lookup %s in %s %d %d\n"
1833 "freevars of %s: %s\n",
1834 PyUnicode_AsUTF8(PyObject_Repr(name)),
1835 PyUnicode_AsUTF8(c->u->u_name),
1836 reftype, arg,
1837 PyUnicode_AsUTF8(co->co_name),
1838 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1839 Py_FatalError("compiler_make_closure()");
1840 }
1841 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001843 flags |= 0x08;
1844 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001846 ADDOP_LOAD_CONST(c, (PyObject*)co);
1847 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
1852static int
1853compiler_decorators(struct compiler *c, asdl_seq* decos)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (!decos)
1858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1861 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1862 }
1863 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864}
1865
1866static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001867compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001869{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001870 /* Push a dict of keyword-only default values.
1871
1872 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1873 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001874 int i;
1875 PyObject *keys = NULL;
1876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1878 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1879 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1880 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001881 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001882 if (!mangled) {
1883 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 if (keys == NULL) {
1886 keys = PyList_New(1);
1887 if (keys == NULL) {
1888 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001889 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001890 }
1891 PyList_SET_ITEM(keys, 0, mangled);
1892 }
1893 else {
1894 int res = PyList_Append(keys, mangled);
1895 Py_DECREF(mangled);
1896 if (res == -1) {
1897 goto error;
1898 }
1899 }
1900 if (!compiler_visit_expr(c, default_)) {
1901 goto error;
1902 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 }
1904 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905 if (keys != NULL) {
1906 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1907 PyObject *keys_tuple = PyList_AsTuple(keys);
1908 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001909 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001911 assert(default_count > 0);
1912 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 }
1914 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001915 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 }
1917
1918error:
1919 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001920 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001921}
1922
1923static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001924compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1925{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001926 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001927 return 1;
1928}
1929
1930static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001931compiler_visit_argannotation(struct compiler *c, identifier id,
1932 expr_ty annotation, PyObject *names)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001935 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001936 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1937 VISIT(c, annexpr, annotation)
1938 }
1939 else {
1940 VISIT(c, expr, annotation);
1941 }
Victor Stinner065efc32014-02-18 22:07:56 +01001942 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001943 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001944 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001945 if (PyList_Append(names, mangled) < 0) {
1946 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001947 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001948 }
1949 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001951 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001952}
1953
1954static int
1955compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1956 PyObject *names)
1957{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001958 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 for (i = 0; i < asdl_seq_LEN(args); i++) {
1960 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001961 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 c,
1963 arg->arg,
1964 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001965 names))
1966 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001968 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001969}
1970
1971static int
1972compiler_visit_annotations(struct compiler *c, arguments_ty args,
1973 expr_ty returns)
1974{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001975 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001976 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001977
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001978 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 */
1980 static identifier return_str;
1981 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001982 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 names = PyList_New(0);
1984 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001985 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001986
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001987 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001989 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001990 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001991 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001993 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001995 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001996 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001997 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (!return_str) {
2001 return_str = PyUnicode_InternFromString("return");
2002 if (!return_str)
2003 goto error;
2004 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002005 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 goto error;
2007 }
2008
2009 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 PyObject *keytuple = PyList_AsTuple(names);
2012 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002013 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002015 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 else {
2018 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002019 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002021
2022error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002024 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002025}
2026
2027static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028compiler_visit_defaults(struct compiler *c, arguments_ty args)
2029{
2030 VISIT_SEQ(c, expr, args->defaults);
2031 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033}
2034
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002035static Py_ssize_t
2036compiler_default_arguments(struct compiler *c, arguments_ty args)
2037{
2038 Py_ssize_t funcflags = 0;
2039 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 if (!compiler_visit_defaults(c, args))
2041 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042 funcflags |= 0x01;
2043 }
2044 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002045 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002046 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002047 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002048 return -1;
2049 }
2050 else if (res > 0) {
2051 funcflags |= 0x02;
2052 }
2053 }
2054 return funcflags;
2055}
2056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057static int
Yury Selivanov75445082015-05-11 22:57:16 -04002058compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002061 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002062 arguments_ty args;
2063 expr_ty returns;
2064 identifier name;
2065 asdl_seq* decos;
2066 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002067 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002068 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002069 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002070 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071
Yury Selivanov75445082015-05-11 22:57:16 -04002072 if (is_async) {
2073 assert(s->kind == AsyncFunctionDef_kind);
2074
2075 args = s->v.AsyncFunctionDef.args;
2076 returns = s->v.AsyncFunctionDef.returns;
2077 decos = s->v.AsyncFunctionDef.decorator_list;
2078 name = s->v.AsyncFunctionDef.name;
2079 body = s->v.AsyncFunctionDef.body;
2080
2081 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2082 } else {
2083 assert(s->kind == FunctionDef_kind);
2084
2085 args = s->v.FunctionDef.args;
2086 returns = s->v.FunctionDef.returns;
2087 decos = s->v.FunctionDef.decorator_list;
2088 name = s->v.FunctionDef.name;
2089 body = s->v.FunctionDef.body;
2090
2091 scope_type = COMPILER_SCOPE_FUNCTION;
2092 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (!compiler_decorators(c, decos))
2095 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002096
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002097 firstlineno = s->lineno;
2098 if (asdl_seq_LEN(decos)) {
2099 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2100 }
2101
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002102 funcflags = compiler_default_arguments(c, args);
2103 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105 }
2106
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002107 annotations = compiler_visit_annotations(c, args, returns);
2108 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 return 0;
2110 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002111 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 funcflags |= 0x04;
2113 }
2114
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002115 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 return 0;
2117 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118
INADA Naokicb41b272017-02-23 00:31:59 +09002119 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002120 if (c->c_optimize < 2) {
2121 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002122 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002123 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 compiler_exit_scope(c);
2125 return 0;
2126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 c->u->u_argcount = asdl_seq_LEN(args->args);
2129 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002130 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002132 qualname = c->u->u_qualname;
2133 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002135 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002136 Py_XDECREF(qualname);
2137 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002139 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002142 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* decorators */
2146 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2147 ADDOP_I(c, CALL_FUNCTION, 1);
2148 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149
Yury Selivanov75445082015-05-11 22:57:16 -04002150 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151}
2152
2153static int
2154compiler_class(struct compiler *c, stmt_ty s)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyCodeObject *co;
2157 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002158 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (!compiler_decorators(c, decos))
2162 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002163
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002164 firstlineno = s->lineno;
2165 if (asdl_seq_LEN(decos)) {
2166 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2167 }
2168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* ultimately generate code for:
2170 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2171 where:
2172 <func> is a function/closure created from the class body;
2173 it has a single argument (__locals__) where the dict
2174 (or MutableSequence) representing the locals is passed
2175 <name> is the class name
2176 <bases> is the positional arguments and *varargs argument
2177 <keywords> is the keyword arguments and **kwds argument
2178 This borrows from compiler_call.
2179 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002182 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002183 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return 0;
2185 /* this block represents what we do in the new scope */
2186 {
2187 /* use the class name for name mangling */
2188 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002189 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* load (global) __name__ ... */
2191 str = PyUnicode_InternFromString("__name__");
2192 if (!str || !compiler_nameop(c, str, Load)) {
2193 Py_XDECREF(str);
2194 compiler_exit_scope(c);
2195 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_DECREF(str);
2198 /* ... and store it as __module__ */
2199 str = PyUnicode_InternFromString("__module__");
2200 if (!str || !compiler_nameop(c, str, Store)) {
2201 Py_XDECREF(str);
2202 compiler_exit_scope(c);
2203 return 0;
2204 }
2205 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002206 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002207 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002208 str = PyUnicode_InternFromString("__qualname__");
2209 if (!str || !compiler_nameop(c, str, Store)) {
2210 Py_XDECREF(str);
2211 compiler_exit_scope(c);
2212 return 0;
2213 }
2214 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002216 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 compiler_exit_scope(c);
2218 return 0;
2219 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002220 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002221 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002222 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002223 str = PyUnicode_InternFromString("__class__");
2224 if (str == NULL) {
2225 compiler_exit_scope(c);
2226 return 0;
2227 }
2228 i = compiler_lookup_arg(c->u->u_cellvars, str);
2229 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002230 if (i < 0) {
2231 compiler_exit_scope(c);
2232 return 0;
2233 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002234 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002237 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002238 str = PyUnicode_InternFromString("__classcell__");
2239 if (!str || !compiler_nameop(c, str, Store)) {
2240 Py_XDECREF(str);
2241 compiler_exit_scope(c);
2242 return 0;
2243 }
2244 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002246 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002247 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002248 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002249 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002250 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002251 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* create the code object */
2253 co = assemble(c, 1);
2254 }
2255 /* leave the new scope */
2256 compiler_exit_scope(c);
2257 if (co == NULL)
2258 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* 2. load the 'build_class' function */
2261 ADDOP(c, LOAD_BUILD_CLASS);
2262
2263 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002264 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 Py_DECREF(co);
2266
2267 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002268 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269
2270 /* 5. generate the rest of the code for the call */
2271 if (!compiler_call_helper(c, 2,
2272 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002273 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 0;
2275
2276 /* 6. apply decorators */
2277 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2278 ADDOP_I(c, CALL_FUNCTION, 1);
2279 }
2280
2281 /* 7. store into <name> */
2282 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2283 return 0;
2284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002287/* Return 0 if the expression is a constant value except named singletons.
2288 Return 1 otherwise. */
2289static int
2290check_is_arg(expr_ty e)
2291{
2292 if (e->kind != Constant_kind) {
2293 return 1;
2294 }
2295 PyObject *value = e->v.Constant.value;
2296 return (value == Py_None
2297 || value == Py_False
2298 || value == Py_True
2299 || value == Py_Ellipsis);
2300}
2301
2302/* Check operands of identity chacks ("is" and "is not").
2303 Emit a warning if any operand is a constant except named singletons.
2304 Return 0 on error.
2305 */
2306static int
2307check_compare(struct compiler *c, expr_ty e)
2308{
2309 Py_ssize_t i, n;
2310 int left = check_is_arg(e->v.Compare.left);
2311 n = asdl_seq_LEN(e->v.Compare.ops);
2312 for (i = 0; i < n; i++) {
2313 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2314 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2315 if (op == Is || op == IsNot) {
2316 if (!right || !left) {
2317 const char *msg = (op == Is)
2318 ? "\"is\" with a literal. Did you mean \"==\"?"
2319 : "\"is not\" with a literal. Did you mean \"!=\"?";
2320 return compiler_warn(c, msg);
2321 }
2322 }
2323 left = right;
2324 }
2325 return 1;
2326}
2327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002329cmpop(cmpop_ty op)
2330{
2331 switch (op) {
2332 case Eq:
2333 return PyCmp_EQ;
2334 case NotEq:
2335 return PyCmp_NE;
2336 case Lt:
2337 return PyCmp_LT;
2338 case LtE:
2339 return PyCmp_LE;
2340 case Gt:
2341 return PyCmp_GT;
2342 case GtE:
2343 return PyCmp_GE;
2344 case Is:
2345 return PyCmp_IS;
2346 case IsNot:
2347 return PyCmp_IS_NOT;
2348 case In:
2349 return PyCmp_IN;
2350 case NotIn:
2351 return PyCmp_NOT_IN;
2352 default:
2353 return PyCmp_BAD;
2354 }
2355}
2356
2357static int
2358compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2359{
2360 switch (e->kind) {
2361 case UnaryOp_kind:
2362 if (e->v.UnaryOp.op == Not)
2363 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2364 /* fallback to general implementation */
2365 break;
2366 case BoolOp_kind: {
2367 asdl_seq *s = e->v.BoolOp.values;
2368 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2369 assert(n >= 0);
2370 int cond2 = e->v.BoolOp.op == Or;
2371 basicblock *next2 = next;
2372 if (!cond2 != !cond) {
2373 next2 = compiler_new_block(c);
2374 if (next2 == NULL)
2375 return 0;
2376 }
2377 for (i = 0; i < n; ++i) {
2378 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2379 return 0;
2380 }
2381 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2382 return 0;
2383 if (next2 != next)
2384 compiler_use_next_block(c, next2);
2385 return 1;
2386 }
2387 case IfExp_kind: {
2388 basicblock *end, *next2;
2389 end = compiler_new_block(c);
2390 if (end == NULL)
2391 return 0;
2392 next2 = compiler_new_block(c);
2393 if (next2 == NULL)
2394 return 0;
2395 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2396 return 0;
2397 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2398 return 0;
2399 ADDOP_JREL(c, JUMP_FORWARD, end);
2400 compiler_use_next_block(c, next2);
2401 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2402 return 0;
2403 compiler_use_next_block(c, end);
2404 return 1;
2405 }
2406 case Compare_kind: {
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002407 if (!check_compare(c, e)) {
2408 return 0;
2409 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002410 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2411 if (n > 0) {
2412 basicblock *cleanup = compiler_new_block(c);
2413 if (cleanup == NULL)
2414 return 0;
2415 VISIT(c, expr, e->v.Compare.left);
2416 for (i = 0; i < n; i++) {
2417 VISIT(c, expr,
2418 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2419 ADDOP(c, DUP_TOP);
2420 ADDOP(c, ROT_THREE);
2421 ADDOP_I(c, COMPARE_OP,
2422 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2423 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2424 NEXT_BLOCK(c);
2425 }
2426 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2427 ADDOP_I(c, COMPARE_OP,
2428 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2429 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2430 basicblock *end = compiler_new_block(c);
2431 if (end == NULL)
2432 return 0;
2433 ADDOP_JREL(c, JUMP_FORWARD, end);
2434 compiler_use_next_block(c, cleanup);
2435 ADDOP(c, POP_TOP);
2436 if (!cond) {
2437 ADDOP_JREL(c, JUMP_FORWARD, next);
2438 }
2439 compiler_use_next_block(c, end);
2440 return 1;
2441 }
2442 /* fallback to general implementation */
2443 break;
2444 }
2445 default:
2446 /* fallback to general implementation */
2447 break;
2448 }
2449
2450 /* general implementation */
2451 VISIT(c, expr, e);
2452 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2453 return 1;
2454}
2455
2456static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002457compiler_ifexp(struct compiler *c, expr_ty e)
2458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 basicblock *end, *next;
2460
2461 assert(e->kind == IfExp_kind);
2462 end = compiler_new_block(c);
2463 if (end == NULL)
2464 return 0;
2465 next = compiler_new_block(c);
2466 if (next == NULL)
2467 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002468 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2469 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 VISIT(c, expr, e->v.IfExp.body);
2471 ADDOP_JREL(c, JUMP_FORWARD, end);
2472 compiler_use_next_block(c, next);
2473 VISIT(c, expr, e->v.IfExp.orelse);
2474 compiler_use_next_block(c, end);
2475 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002476}
2477
2478static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479compiler_lambda(struct compiler *c, expr_ty e)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002482 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002484 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 arguments_ty args = e->v.Lambda.args;
2486 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (!name) {
2489 name = PyUnicode_InternFromString("<lambda>");
2490 if (!name)
2491 return 0;
2492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002494 funcflags = compiler_default_arguments(c, args);
2495 if (funcflags == -1) {
2496 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002498
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002499 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002500 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* Make None the first constant, so the lambda can't have a
2504 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002505 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 c->u->u_argcount = asdl_seq_LEN(args->args);
2509 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2510 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2511 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002512 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 }
2514 else {
2515 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002516 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002518 qualname = c->u->u_qualname;
2519 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002521 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002524 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002525 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Py_DECREF(co);
2527
2528 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529}
2530
2531static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532compiler_if(struct compiler *c, stmt_ty s)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 basicblock *end, *next;
2535 int constant;
2536 assert(s->kind == If_kind);
2537 end = compiler_new_block(c);
2538 if (end == NULL)
2539 return 0;
2540
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002541 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* constant = 0: "if 0"
2543 * constant = 1: "if 1", "if 2", ...
2544 * constant = -1: rest */
2545 if (constant == 0) {
2546 if (s->v.If.orelse)
2547 VISIT_SEQ(c, stmt, s->v.If.orelse);
2548 } else if (constant == 1) {
2549 VISIT_SEQ(c, stmt, s->v.If.body);
2550 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002551 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 next = compiler_new_block(c);
2553 if (next == NULL)
2554 return 0;
2555 }
2556 else
2557 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002558 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2559 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002561 if (asdl_seq_LEN(s->v.If.orelse)) {
2562 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 compiler_use_next_block(c, next);
2564 VISIT_SEQ(c, stmt, s->v.If.orelse);
2565 }
2566 }
2567 compiler_use_next_block(c, end);
2568 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569}
2570
2571static int
2572compiler_for(struct compiler *c, stmt_ty s)
2573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 start = compiler_new_block(c);
2577 cleanup = compiler_new_block(c);
2578 end = compiler_new_block(c);
2579 if (start == NULL || end == NULL || cleanup == NULL)
2580 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002581
2582 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 VISIT(c, expr, s->v.For.iter);
2586 ADDOP(c, GET_ITER);
2587 compiler_use_next_block(c, start);
2588 ADDOP_JREL(c, FOR_ITER, cleanup);
2589 VISIT(c, expr, s->v.For.target);
2590 VISIT_SEQ(c, stmt, s->v.For.body);
2591 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2592 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002593
2594 compiler_pop_fblock(c, FOR_LOOP, start);
2595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 VISIT_SEQ(c, stmt, s->v.For.orelse);
2597 compiler_use_next_block(c, end);
2598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599}
2600
Yury Selivanov75445082015-05-11 22:57:16 -04002601
2602static int
2603compiler_async_for(struct compiler *c, stmt_ty s)
2604{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002605 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002606 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2607 return compiler_error(c, "'async for' outside async function");
2608 }
2609
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002610 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002611 except = compiler_new_block(c);
2612 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002613
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002614 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002615 return 0;
2616
2617 VISIT(c, expr, s->v.AsyncFor.iter);
2618 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002619
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002620 compiler_use_next_block(c, start);
2621 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2622 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002623
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002624 /* SETUP_FINALLY to guard the __anext__ call */
2625 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002626 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002627 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002628 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002629 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002630
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002631 /* Success block for __anext__ */
2632 VISIT(c, expr, s->v.AsyncFor.target);
2633 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2634 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2635
2636 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002637
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002638 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002639 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002640 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002641
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002642 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002643 VISIT_SEQ(c, stmt, s->v.For.orelse);
2644
2645 compiler_use_next_block(c, end);
2646
2647 return 1;
2648}
2649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650static int
2651compiler_while(struct compiler *c, stmt_ty s)
2652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002654 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (constant == 0) {
2657 if (s->v.While.orelse)
2658 VISIT_SEQ(c, stmt, s->v.While.orelse);
2659 return 1;
2660 }
2661 loop = compiler_new_block(c);
2662 end = compiler_new_block(c);
2663 if (constant == -1) {
2664 anchor = compiler_new_block(c);
2665 if (anchor == NULL)
2666 return 0;
2667 }
2668 if (loop == NULL || end == NULL)
2669 return 0;
2670 if (s->v.While.orelse) {
2671 orelse = compiler_new_block(c);
2672 if (orelse == NULL)
2673 return 0;
2674 }
2675 else
2676 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002679 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 return 0;
2681 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002682 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2683 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 }
2685 VISIT_SEQ(c, stmt, s->v.While.body);
2686 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* XXX should the two POP instructions be in a separate block
2689 if there is no else clause ?
2690 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002692 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002694 compiler_pop_fblock(c, WHILE_LOOP, loop);
2695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (orelse != NULL) /* what if orelse is just pass? */
2697 VISIT_SEQ(c, stmt, s->v.While.orelse);
2698 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701}
2702
2703static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002704compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002706 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002707 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002708 if (c->u->u_ste->ste_type != FunctionBlock)
2709 return compiler_error(c, "'return' outside function");
2710 if (s->v.Return.value != NULL &&
2711 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2712 {
2713 return compiler_error(
2714 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002716 if (preserve_tos) {
2717 VISIT(c, expr, s->v.Return.value);
2718 }
2719 for (int depth = c->u->u_nfblocks; depth--;) {
2720 struct fblockinfo *info = &c->u->u_fblock[depth];
2721
2722 if (!compiler_unwind_fblock(c, info, preserve_tos))
2723 return 0;
2724 }
2725 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002726 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002727 }
2728 else if (!preserve_tos) {
2729 VISIT(c, expr, s->v.Return.value);
2730 }
2731 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734}
2735
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002736static int
2737compiler_break(struct compiler *c)
2738{
2739 for (int depth = c->u->u_nfblocks; depth--;) {
2740 struct fblockinfo *info = &c->u->u_fblock[depth];
2741
2742 if (!compiler_unwind_fblock(c, info, 0))
2743 return 0;
2744 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2745 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2746 return 1;
2747 }
2748 }
2749 return compiler_error(c, "'break' outside loop");
2750}
2751
2752static int
2753compiler_continue(struct compiler *c)
2754{
2755 for (int depth = c->u->u_nfblocks; depth--;) {
2756 struct fblockinfo *info = &c->u->u_fblock[depth];
2757
2758 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2759 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2760 return 1;
2761 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002762 if (!compiler_unwind_fblock(c, info, 0))
2763 return 0;
2764 }
2765 return compiler_error(c, "'continue' not properly in loop");
2766}
2767
2768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770
2771 SETUP_FINALLY L
2772 <code for body>
2773 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 BEGIN_FINALLY
2775 L:
2776 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 END_FINALLY
2778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 The special instructions use the block stack. Each block
2780 stack entry contains the instruction that created it (here
2781 SETUP_FINALLY), the level of the value stack at the time the
2782 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 Pushes the current value stack level and the label
2786 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 Pops en entry from the block stack.
2789 BEGIN_FINALLY
2790 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2793 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002796 when a SETUP_FINALLY entry is found, the raised and the caught
2797 exceptions are pushed onto the value stack (and the exception
2798 condition is cleared), and the interpreter jumps to the label
2799 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800*/
2801
2802static int
2803compiler_try_finally(struct compiler *c, stmt_ty s)
2804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 body = compiler_new_block(c);
2808 end = compiler_new_block(c);
2809 if (body == NULL || end == NULL)
2810 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002812 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 ADDOP_JREL(c, SETUP_FINALLY, end);
2814 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002815 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002817 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2818 if (!compiler_try_except(c, s))
2819 return 0;
2820 }
2821 else {
2822 VISIT_SEQ(c, stmt, s->v.Try.body);
2823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002828 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002830 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002832 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 ADDOP(c, END_FINALLY);
2834 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836}
2837
2838/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002839 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 (The contents of the value stack is shown in [], with the top
2841 at the right; 'tb' is trace-back info, 'val' the exception's
2842 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843
2844 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 [] <code for S>
2847 [] POP_BLOCK
2848 [] JUMP_FORWARD L0
2849
2850 [tb, val, exc] L1: DUP )
2851 [tb, val, exc, exc] <evaluate E1> )
2852 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2853 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2854 [tb, val, exc] POP
2855 [tb, val] <assign to V1> (or POP if no V1)
2856 [tb] POP
2857 [] <code for S1>
2858 JUMP_FORWARD L0
2859
2860 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 .............................etc.......................
2862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2864
2865 [] L0: <next statement>
2866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 Of course, parts are not generated if Vi or Ei is not present.
2868*/
2869static int
2870compiler_try_except(struct compiler *c, stmt_ty s)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002873 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 body = compiler_new_block(c);
2876 except = compiler_new_block(c);
2877 orelse = compiler_new_block(c);
2878 end = compiler_new_block(c);
2879 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2880 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002885 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 ADDOP(c, POP_BLOCK);
2887 compiler_pop_fblock(c, EXCEPT, body);
2888 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002889 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 compiler_use_next_block(c, except);
2891 for (i = 0; i < n; i++) {
2892 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002893 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (!handler->v.ExceptHandler.type && i < n-1)
2895 return compiler_error(c, "default 'except:' must be last");
2896 c->u->u_lineno_set = 0;
2897 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002898 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 except = compiler_new_block(c);
2900 if (except == NULL)
2901 return 0;
2902 if (handler->v.ExceptHandler.type) {
2903 ADDOP(c, DUP_TOP);
2904 VISIT(c, expr, handler->v.ExceptHandler.type);
2905 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2906 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2907 }
2908 ADDOP(c, POP_TOP);
2909 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002910 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002911
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002912 cleanup_end = compiler_new_block(c);
2913 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002914 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002915 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002916 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002917
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002918 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2919 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002921 /*
2922 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002923 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002924 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002925 try:
2926 # body
2927 finally:
2928 name = None
2929 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002930 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002932 /* second try: */
2933 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2934 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002935 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002936 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002938 /* second # body */
2939 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2940 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 ADDOP(c, BEGIN_FINALLY);
2942 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002944 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002945 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002947 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002949 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002950 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002951 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002952 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002954 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002955 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002956 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 }
2958 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002959 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002961 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002962 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002963 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964
Guido van Rossumb940e112007-01-10 16:19:56 +00002965 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002966 ADDOP(c, POP_TOP);
2967 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002968 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002971 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002972 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 }
2974 ADDOP_JREL(c, JUMP_FORWARD, end);
2975 compiler_use_next_block(c, except);
2976 }
2977 ADDOP(c, END_FINALLY);
2978 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002979 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 compiler_use_next_block(c, end);
2981 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002985compiler_try(struct compiler *c, stmt_ty s) {
2986 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2987 return compiler_try_finally(c, s);
2988 else
2989 return compiler_try_except(c, s);
2990}
2991
2992
2993static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994compiler_import_as(struct compiler *c, identifier name, identifier asname)
2995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 /* The IMPORT_NAME opcode was already generated. This function
2997 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003000 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003002 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3003 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003004 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003005 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003008 while (1) {
3009 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003011 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003012 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003013 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003014 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003016 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003017 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003018 if (dot == -1) {
3019 break;
3020 }
3021 ADDOP(c, ROT_TWO);
3022 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003024 if (!compiler_nameop(c, asname, Store)) {
3025 return 0;
3026 }
3027 ADDOP(c, POP_TOP);
3028 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 }
3030 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031}
3032
3033static int
3034compiler_import(struct compiler *c, stmt_ty s)
3035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 /* The Import node stores a module name like a.b.c as a single
3037 string. This is convenient for all cases except
3038 import a.b.c as d
3039 where we need to parse that string to extract the individual
3040 module names.
3041 XXX Perhaps change the representation to make this case simpler?
3042 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003043 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 for (i = 0; i < n; i++) {
3046 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3047 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003049 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3050 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 if (alias->asname) {
3054 r = compiler_import_as(c, alias->name, alias->asname);
3055 if (!r)
3056 return r;
3057 }
3058 else {
3059 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003060 Py_ssize_t dot = PyUnicode_FindChar(
3061 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003062 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003063 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003064 if (tmp == NULL)
3065 return 0;
3066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003068 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 Py_DECREF(tmp);
3070 }
3071 if (!r)
3072 return r;
3073 }
3074 }
3075 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076}
3077
3078static int
3079compiler_from_import(struct compiler *c, stmt_ty s)
3080{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003081 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003082 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 if (!empty_string) {
3086 empty_string = PyUnicode_FromString("");
3087 if (!empty_string)
3088 return 0;
3089 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003091 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003092
3093 names = PyTuple_New(n);
3094 if (!names)
3095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 /* build up the names */
3098 for (i = 0; i < n; i++) {
3099 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3100 Py_INCREF(alias->name);
3101 PyTuple_SET_ITEM(names, i, alias->name);
3102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003105 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 Py_DECREF(names);
3107 return compiler_error(c, "from __future__ imports must occur "
3108 "at the beginning of the file");
3109 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003110 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 if (s->v.ImportFrom.module) {
3113 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3114 }
3115 else {
3116 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3117 }
3118 for (i = 0; i < n; i++) {
3119 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3120 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003122 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 assert(n == 1);
3124 ADDOP(c, IMPORT_STAR);
3125 return 1;
3126 }
3127
3128 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3129 store_name = alias->name;
3130 if (alias->asname)
3131 store_name = alias->asname;
3132
3133 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 return 0;
3135 }
3136 }
3137 /* remove imported module */
3138 ADDOP(c, POP_TOP);
3139 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140}
3141
3142static int
3143compiler_assert(struct compiler *c, stmt_ty s)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 static PyObject *assertion_error = NULL;
3146 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147
Georg Brandl8334fd92010-12-04 10:26:46 +00003148 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 return 1;
3150 if (assertion_error == NULL) {
3151 assertion_error = PyUnicode_InternFromString("AssertionError");
3152 if (assertion_error == NULL)
3153 return 0;
3154 }
3155 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003156 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3157 {
3158 if (!compiler_warn(c, "assertion is always true, "
3159 "perhaps remove parentheses?"))
3160 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003161 return 0;
3162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 end = compiler_new_block(c);
3165 if (end == NULL)
3166 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003167 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3168 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3170 if (s->v.Assert.msg) {
3171 VISIT(c, expr, s->v.Assert.msg);
3172 ADDOP_I(c, CALL_FUNCTION, 1);
3173 }
3174 ADDOP_I(c, RAISE_VARARGS, 1);
3175 compiler_use_next_block(c, end);
3176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177}
3178
3179static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003180compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3181{
3182 if (c->c_interactive && c->c_nestlevel <= 1) {
3183 VISIT(c, expr, value);
3184 ADDOP(c, PRINT_EXPR);
3185 return 1;
3186 }
3187
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003188 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003189 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003190 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003191 }
3192
3193 VISIT(c, expr, value);
3194 ADDOP(c, POP_TOP);
3195 return 1;
3196}
3197
3198static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199compiler_visit_stmt(struct compiler *c, stmt_ty s)
3200{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003201 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* Always assign a lineno to the next instruction for a stmt. */
3204 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003205 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 switch (s->kind) {
3209 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003210 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 case ClassDef_kind:
3212 return compiler_class(c, s);
3213 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003214 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 case Delete_kind:
3216 VISIT_SEQ(c, expr, s->v.Delete.targets)
3217 break;
3218 case Assign_kind:
3219 n = asdl_seq_LEN(s->v.Assign.targets);
3220 VISIT(c, expr, s->v.Assign.value);
3221 for (i = 0; i < n; i++) {
3222 if (i < n - 1)
3223 ADDOP(c, DUP_TOP);
3224 VISIT(c, expr,
3225 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3226 }
3227 break;
3228 case AugAssign_kind:
3229 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003230 case AnnAssign_kind:
3231 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 case For_kind:
3233 return compiler_for(c, s);
3234 case While_kind:
3235 return compiler_while(c, s);
3236 case If_kind:
3237 return compiler_if(c, s);
3238 case Raise_kind:
3239 n = 0;
3240 if (s->v.Raise.exc) {
3241 VISIT(c, expr, s->v.Raise.exc);
3242 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003243 if (s->v.Raise.cause) {
3244 VISIT(c, expr, s->v.Raise.cause);
3245 n++;
3246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003248 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003250 case Try_kind:
3251 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 case Assert_kind:
3253 return compiler_assert(c, s);
3254 case Import_kind:
3255 return compiler_import(c, s);
3256 case ImportFrom_kind:
3257 return compiler_from_import(c, s);
3258 case Global_kind:
3259 case Nonlocal_kind:
3260 break;
3261 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003262 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 case Pass_kind:
3264 break;
3265 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003266 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 case Continue_kind:
3268 return compiler_continue(c);
3269 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003270 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003271 case AsyncFunctionDef_kind:
3272 return compiler_function(c, s, 1);
3273 case AsyncWith_kind:
3274 return compiler_async_with(c, s, 0);
3275 case AsyncFor_kind:
3276 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 }
Yury Selivanov75445082015-05-11 22:57:16 -04003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280}
3281
3282static int
3283unaryop(unaryop_ty op)
3284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 switch (op) {
3286 case Invert:
3287 return UNARY_INVERT;
3288 case Not:
3289 return UNARY_NOT;
3290 case UAdd:
3291 return UNARY_POSITIVE;
3292 case USub:
3293 return UNARY_NEGATIVE;
3294 default:
3295 PyErr_Format(PyExc_SystemError,
3296 "unary op %d should not be possible", op);
3297 return 0;
3298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299}
3300
3301static int
3302binop(struct compiler *c, operator_ty op)
3303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 switch (op) {
3305 case Add:
3306 return BINARY_ADD;
3307 case Sub:
3308 return BINARY_SUBTRACT;
3309 case Mult:
3310 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003311 case MatMult:
3312 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 case Div:
3314 return BINARY_TRUE_DIVIDE;
3315 case Mod:
3316 return BINARY_MODULO;
3317 case Pow:
3318 return BINARY_POWER;
3319 case LShift:
3320 return BINARY_LSHIFT;
3321 case RShift:
3322 return BINARY_RSHIFT;
3323 case BitOr:
3324 return BINARY_OR;
3325 case BitXor:
3326 return BINARY_XOR;
3327 case BitAnd:
3328 return BINARY_AND;
3329 case FloorDiv:
3330 return BINARY_FLOOR_DIVIDE;
3331 default:
3332 PyErr_Format(PyExc_SystemError,
3333 "binary op %d should not be possible", op);
3334 return 0;
3335 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336}
3337
3338static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339inplace_binop(struct compiler *c, operator_ty op)
3340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 switch (op) {
3342 case Add:
3343 return INPLACE_ADD;
3344 case Sub:
3345 return INPLACE_SUBTRACT;
3346 case Mult:
3347 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003348 case MatMult:
3349 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 case Div:
3351 return INPLACE_TRUE_DIVIDE;
3352 case Mod:
3353 return INPLACE_MODULO;
3354 case Pow:
3355 return INPLACE_POWER;
3356 case LShift:
3357 return INPLACE_LSHIFT;
3358 case RShift:
3359 return INPLACE_RSHIFT;
3360 case BitOr:
3361 return INPLACE_OR;
3362 case BitXor:
3363 return INPLACE_XOR;
3364 case BitAnd:
3365 return INPLACE_AND;
3366 case FloorDiv:
3367 return INPLACE_FLOOR_DIVIDE;
3368 default:
3369 PyErr_Format(PyExc_SystemError,
3370 "inplace binary op %d should not be possible", op);
3371 return 0;
3372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373}
3374
3375static int
3376compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3377{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003378 int op, scope;
3379 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 PyObject *dict = c->u->u_names;
3383 PyObject *mangled;
3384 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003386 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3387 !_PyUnicode_EqualToASCIIString(name, "True") &&
3388 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003389
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003390 mangled = _Py_Mangle(c->u->u_private, name);
3391 if (!mangled)
3392 return 0;
3393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 op = 0;
3395 optype = OP_NAME;
3396 scope = PyST_GetScope(c->u->u_ste, mangled);
3397 switch (scope) {
3398 case FREE:
3399 dict = c->u->u_freevars;
3400 optype = OP_DEREF;
3401 break;
3402 case CELL:
3403 dict = c->u->u_cellvars;
3404 optype = OP_DEREF;
3405 break;
3406 case LOCAL:
3407 if (c->u->u_ste->ste_type == FunctionBlock)
3408 optype = OP_FAST;
3409 break;
3410 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003411 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 optype = OP_GLOBAL;
3413 break;
3414 case GLOBAL_EXPLICIT:
3415 optype = OP_GLOBAL;
3416 break;
3417 default:
3418 /* scope can be 0 */
3419 break;
3420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003423 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 switch (optype) {
3426 case OP_DEREF:
3427 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003428 case Load:
3429 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3430 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 case Store: op = STORE_DEREF; break;
3432 case AugLoad:
3433 case AugStore:
3434 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003435 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 case Param:
3437 default:
3438 PyErr_SetString(PyExc_SystemError,
3439 "param invalid for deref variable");
3440 return 0;
3441 }
3442 break;
3443 case OP_FAST:
3444 switch (ctx) {
3445 case Load: op = LOAD_FAST; break;
3446 case Store: op = STORE_FAST; break;
3447 case Del: op = DELETE_FAST; break;
3448 case AugLoad:
3449 case AugStore:
3450 break;
3451 case Param:
3452 default:
3453 PyErr_SetString(PyExc_SystemError,
3454 "param invalid for local variable");
3455 return 0;
3456 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003457 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 return 1;
3459 case OP_GLOBAL:
3460 switch (ctx) {
3461 case Load: op = LOAD_GLOBAL; break;
3462 case Store: op = STORE_GLOBAL; break;
3463 case Del: op = DELETE_GLOBAL; break;
3464 case AugLoad:
3465 case AugStore:
3466 break;
3467 case Param:
3468 default:
3469 PyErr_SetString(PyExc_SystemError,
3470 "param invalid for global variable");
3471 return 0;
3472 }
3473 break;
3474 case OP_NAME:
3475 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003476 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 case Store: op = STORE_NAME; break;
3478 case Del: op = DELETE_NAME; break;
3479 case AugLoad:
3480 case AugStore:
3481 break;
3482 case Param:
3483 default:
3484 PyErr_SetString(PyExc_SystemError,
3485 "param invalid for name variable");
3486 return 0;
3487 }
3488 break;
3489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 assert(op);
3492 arg = compiler_add_o(c, dict, mangled);
3493 Py_DECREF(mangled);
3494 if (arg < 0)
3495 return 0;
3496 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497}
3498
3499static int
3500compiler_boolop(struct compiler *c, expr_ty e)
3501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003503 int jumpi;
3504 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 assert(e->kind == BoolOp_kind);
3508 if (e->v.BoolOp.op == And)
3509 jumpi = JUMP_IF_FALSE_OR_POP;
3510 else
3511 jumpi = JUMP_IF_TRUE_OR_POP;
3512 end = compiler_new_block(c);
3513 if (end == NULL)
3514 return 0;
3515 s = e->v.BoolOp.values;
3516 n = asdl_seq_LEN(s) - 1;
3517 assert(n >= 0);
3518 for (i = 0; i < n; ++i) {
3519 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3520 ADDOP_JABS(c, jumpi, end);
3521 }
3522 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3523 compiler_use_next_block(c, end);
3524 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525}
3526
3527static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003528starunpack_helper(struct compiler *c, asdl_seq *elts,
3529 int single_op, int inner_op, int outer_op)
3530{
3531 Py_ssize_t n = asdl_seq_LEN(elts);
3532 Py_ssize_t i, nsubitems = 0, nseen = 0;
3533 for (i = 0; i < n; i++) {
3534 expr_ty elt = asdl_seq_GET(elts, i);
3535 if (elt->kind == Starred_kind) {
3536 if (nseen) {
3537 ADDOP_I(c, inner_op, nseen);
3538 nseen = 0;
3539 nsubitems++;
3540 }
3541 VISIT(c, expr, elt->v.Starred.value);
3542 nsubitems++;
3543 }
3544 else {
3545 VISIT(c, expr, elt);
3546 nseen++;
3547 }
3548 }
3549 if (nsubitems) {
3550 if (nseen) {
3551 ADDOP_I(c, inner_op, nseen);
3552 nsubitems++;
3553 }
3554 ADDOP_I(c, outer_op, nsubitems);
3555 }
3556 else
3557 ADDOP_I(c, single_op, nseen);
3558 return 1;
3559}
3560
3561static int
3562assignment_helper(struct compiler *c, asdl_seq *elts)
3563{
3564 Py_ssize_t n = asdl_seq_LEN(elts);
3565 Py_ssize_t i;
3566 int seen_star = 0;
3567 for (i = 0; i < n; i++) {
3568 expr_ty elt = asdl_seq_GET(elts, i);
3569 if (elt->kind == Starred_kind && !seen_star) {
3570 if ((i >= (1 << 8)) ||
3571 (n-i-1 >= (INT_MAX >> 8)))
3572 return compiler_error(c,
3573 "too many expressions in "
3574 "star-unpacking assignment");
3575 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3576 seen_star = 1;
3577 asdl_seq_SET(elts, i, elt->v.Starred.value);
3578 }
3579 else if (elt->kind == Starred_kind) {
3580 return compiler_error(c,
3581 "two starred expressions in assignment");
3582 }
3583 }
3584 if (!seen_star) {
3585 ADDOP_I(c, UNPACK_SEQUENCE, n);
3586 }
3587 VISIT_SEQ(c, expr, elts);
3588 return 1;
3589}
3590
3591static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592compiler_list(struct compiler *c, expr_ty e)
3593{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003594 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003596 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003598 else if (e->v.List.ctx == Load) {
3599 return starunpack_helper(c, elts,
3600 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003602 else
3603 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605}
3606
3607static int
3608compiler_tuple(struct compiler *c, expr_ty e)
3609{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003610 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003612 return assignment_helper(c, elts);
3613 }
3614 else if (e->v.Tuple.ctx == Load) {
3615 return starunpack_helper(c, elts,
3616 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3617 }
3618 else
3619 VISIT_SEQ(c, expr, elts);
3620 return 1;
3621}
3622
3623static int
3624compiler_set(struct compiler *c, expr_ty e)
3625{
3626 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3627 BUILD_SET, BUILD_SET_UNPACK);
3628}
3629
3630static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003631are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3632{
3633 Py_ssize_t i;
3634 for (i = begin; i < end; i++) {
3635 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003636 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003637 return 0;
3638 }
3639 return 1;
3640}
3641
3642static int
3643compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3644{
3645 Py_ssize_t i, n = end - begin;
3646 PyObject *keys, *key;
3647 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3648 for (i = begin; i < end; i++) {
3649 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3650 }
3651 keys = PyTuple_New(n);
3652 if (keys == NULL) {
3653 return 0;
3654 }
3655 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003656 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003657 Py_INCREF(key);
3658 PyTuple_SET_ITEM(keys, i - begin, key);
3659 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003660 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003661 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3662 }
3663 else {
3664 for (i = begin; i < end; i++) {
3665 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3666 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3667 }
3668 ADDOP_I(c, BUILD_MAP, n);
3669 }
3670 return 1;
3671}
3672
3673static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003674compiler_dict(struct compiler *c, expr_ty e)
3675{
Victor Stinner976bb402016-03-23 11:36:19 +01003676 Py_ssize_t i, n, elements;
3677 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003678 int is_unpacking = 0;
3679 n = asdl_seq_LEN(e->v.Dict.values);
3680 containers = 0;
3681 elements = 0;
3682 for (i = 0; i < n; i++) {
3683 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3684 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003685 if (!compiler_subdict(c, e, i - elements, i))
3686 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 containers++;
3688 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003690 if (is_unpacking) {
3691 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3692 containers++;
3693 }
3694 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003695 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 }
3697 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003698 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003699 if (!compiler_subdict(c, e, n - elements, n))
3700 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003701 containers++;
3702 }
3703 /* If there is more than one dict, they need to be merged into a new
3704 * dict. If there is one dict and it's an unpacking, then it needs
3705 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003706 if (containers > 1 || is_unpacking) {
3707 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 }
3709 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710}
3711
3712static int
3713compiler_compare(struct compiler *c, expr_ty e)
3714{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003715 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003717 if (!check_compare(c, e)) {
3718 return 0;
3719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003721 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3722 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3723 if (n == 0) {
3724 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3725 ADDOP_I(c, COMPARE_OP,
3726 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3727 }
3728 else {
3729 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 if (cleanup == NULL)
3731 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003732 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 VISIT(c, expr,
3734 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003735 ADDOP(c, DUP_TOP);
3736 ADDOP(c, ROT_THREE);
3737 ADDOP_I(c, COMPARE_OP,
3738 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3739 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3740 NEXT_BLOCK(c);
3741 }
3742 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3743 ADDOP_I(c, COMPARE_OP,
3744 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 basicblock *end = compiler_new_block(c);
3746 if (end == NULL)
3747 return 0;
3748 ADDOP_JREL(c, JUMP_FORWARD, end);
3749 compiler_use_next_block(c, cleanup);
3750 ADDOP(c, ROT_TWO);
3751 ADDOP(c, POP_TOP);
3752 compiler_use_next_block(c, end);
3753 }
3754 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755}
3756
3757static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003758maybe_optimize_method_call(struct compiler *c, expr_ty e)
3759{
3760 Py_ssize_t argsl, i;
3761 expr_ty meth = e->v.Call.func;
3762 asdl_seq *args = e->v.Call.args;
3763
3764 /* Check that the call node is an attribute access, and that
3765 the call doesn't have keyword parameters. */
3766 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3767 asdl_seq_LEN(e->v.Call.keywords))
3768 return -1;
3769
3770 /* Check that there are no *varargs types of arguments. */
3771 argsl = asdl_seq_LEN(args);
3772 for (i = 0; i < argsl; i++) {
3773 expr_ty elt = asdl_seq_GET(args, i);
3774 if (elt->kind == Starred_kind) {
3775 return -1;
3776 }
3777 }
3778
3779 /* Alright, we can optimize the code. */
3780 VISIT(c, expr, meth->v.Attribute.value);
3781 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3782 VISIT_SEQ(c, expr, e->v.Call.args);
3783 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3784 return 1;
3785}
3786
3787static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788compiler_call(struct compiler *c, expr_ty e)
3789{
Yury Selivanovf2392132016-12-13 19:03:51 -05003790 if (maybe_optimize_method_call(c, e) > 0)
3791 return 1;
3792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 VISIT(c, expr, e->v.Call.func);
3794 return compiler_call_helper(c, 0,
3795 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003797}
3798
Eric V. Smith235a6f02015-09-19 14:51:32 -04003799static int
3800compiler_joined_str(struct compiler *c, expr_ty e)
3801{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003802 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003803 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3804 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003805 return 1;
3806}
3807
Eric V. Smitha78c7952015-11-03 12:45:05 -05003808/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003809static int
3810compiler_formatted_value(struct compiler *c, expr_ty e)
3811{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003812 /* Our oparg encodes 2 pieces of information: the conversion
3813 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003814
Eric V. Smitha78c7952015-11-03 12:45:05 -05003815 Convert the conversion char to 2 bits:
3816 None: 000 0x0 FVC_NONE
3817 !s : 001 0x1 FVC_STR
3818 !r : 010 0x2 FVC_REPR
3819 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003820
Eric V. Smitha78c7952015-11-03 12:45:05 -05003821 next bit is whether or not we have a format spec:
3822 yes : 100 0x4
3823 no : 000 0x0
3824 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003825
Eric V. Smitha78c7952015-11-03 12:45:05 -05003826 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003827
Eric V. Smitha78c7952015-11-03 12:45:05 -05003828 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003829 VISIT(c, expr, e->v.FormattedValue.value);
3830
Eric V. Smitha78c7952015-11-03 12:45:05 -05003831 switch (e->v.FormattedValue.conversion) {
3832 case 's': oparg = FVC_STR; break;
3833 case 'r': oparg = FVC_REPR; break;
3834 case 'a': oparg = FVC_ASCII; break;
3835 case -1: oparg = FVC_NONE; break;
3836 default:
3837 PyErr_SetString(PyExc_SystemError,
3838 "Unrecognized conversion character");
3839 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003840 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003841 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003842 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003843 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003844 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003845 }
3846
Eric V. Smitha78c7952015-11-03 12:45:05 -05003847 /* And push our opcode and oparg */
3848 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003849 return 1;
3850}
3851
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003852static int
3853compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3854{
3855 Py_ssize_t i, n = end - begin;
3856 keyword_ty kw;
3857 PyObject *keys, *key;
3858 assert(n > 0);
3859 if (n > 1) {
3860 for (i = begin; i < end; i++) {
3861 kw = asdl_seq_GET(keywords, i);
3862 VISIT(c, expr, kw->value);
3863 }
3864 keys = PyTuple_New(n);
3865 if (keys == NULL) {
3866 return 0;
3867 }
3868 for (i = begin; i < end; i++) {
3869 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3870 Py_INCREF(key);
3871 PyTuple_SET_ITEM(keys, i - begin, key);
3872 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003873 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003874 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3875 }
3876 else {
3877 /* a for loop only executes once */
3878 for (i = begin; i < end; i++) {
3879 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003880 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003881 VISIT(c, expr, kw->value);
3882 }
3883 ADDOP_I(c, BUILD_MAP, n);
3884 }
3885 return 1;
3886}
3887
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003888/* shared code between compiler_call and compiler_class */
3889static int
3890compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003891 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003892 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003893 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003894{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003895 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003896 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003897
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003898 /* the number of tuples and dictionaries on the stack */
3899 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3900
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003901 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003902 nkwelts = asdl_seq_LEN(keywords);
3903
3904 for (i = 0; i < nkwelts; i++) {
3905 keyword_ty kw = asdl_seq_GET(keywords, i);
3906 if (kw->arg == NULL) {
3907 mustdictunpack = 1;
3908 break;
3909 }
3910 }
3911
3912 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003913 for (i = 0; i < nelts; i++) {
3914 expr_ty elt = asdl_seq_GET(args, i);
3915 if (elt->kind == Starred_kind) {
3916 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003917 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003918 if (nseen) {
3919 ADDOP_I(c, BUILD_TUPLE, nseen);
3920 nseen = 0;
3921 nsubargs++;
3922 }
3923 VISIT(c, expr, elt->v.Starred.value);
3924 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003925 }
3926 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003927 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003928 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003929 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003931
3932 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003933 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003934 if (nseen) {
3935 /* Pack up any trailing positional arguments. */
3936 ADDOP_I(c, BUILD_TUPLE, nseen);
3937 nsubargs++;
3938 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003939 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003940 /* If we ended up with more than one stararg, we need
3941 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003942 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003943 }
3944 else if (nsubargs == 0) {
3945 ADDOP_I(c, BUILD_TUPLE, 0);
3946 }
3947 nseen = 0; /* the number of keyword arguments on the stack following */
3948 for (i = 0; i < nkwelts; i++) {
3949 keyword_ty kw = asdl_seq_GET(keywords, i);
3950 if (kw->arg == NULL) {
3951 /* A keyword argument unpacking. */
3952 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003953 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3954 return 0;
3955 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003956 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003957 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003958 VISIT(c, expr, kw->value);
3959 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003960 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003961 else {
3962 nseen++;
3963 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003964 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003965 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003966 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003967 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003968 return 0;
3969 nsubkwargs++;
3970 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003971 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003972 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003973 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003974 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003975 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3976 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003978 else if (nkwelts) {
3979 PyObject *names;
3980 VISIT_SEQ(c, keyword, keywords);
3981 names = PyTuple_New(nkwelts);
3982 if (names == NULL) {
3983 return 0;
3984 }
3985 for (i = 0; i < nkwelts; i++) {
3986 keyword_ty kw = asdl_seq_GET(keywords, i);
3987 Py_INCREF(kw->arg);
3988 PyTuple_SET_ITEM(names, i, kw->arg);
3989 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003990 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003991 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3992 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003994 else {
3995 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3996 return 1;
3997 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003998}
3999
Nick Coghlan650f0d02007-04-15 12:05:43 +00004000
4001/* List and set comprehensions and generator expressions work by creating a
4002 nested function to perform the actual iteration. This means that the
4003 iteration variables don't leak into the current scope.
4004 The defined function is called immediately following its definition, with the
4005 result of that call being the result of the expression.
4006 The LC/SC version returns the populated container, while the GE version is
4007 flagged in symtable.c as a generator, so it returns the generator object
4008 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004009
4010 Possible cleanups:
4011 - iterate over the generator sequence instead of using recursion
4012*/
4013
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004014
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004015static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016compiler_comprehension_generator(struct compiler *c,
4017 asdl_seq *generators, int gen_index,
4018 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004020 comprehension_ty gen;
4021 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4022 if (gen->is_async) {
4023 return compiler_async_comprehension_generator(
4024 c, generators, gen_index, elt, val, type);
4025 } else {
4026 return compiler_sync_comprehension_generator(
4027 c, generators, gen_index, elt, val, type);
4028 }
4029}
4030
4031static int
4032compiler_sync_comprehension_generator(struct compiler *c,
4033 asdl_seq *generators, int gen_index,
4034 expr_ty elt, expr_ty val, int type)
4035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 /* generate code for the iterator, then each of the ifs,
4037 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 comprehension_ty gen;
4040 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004041 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 start = compiler_new_block(c);
4044 skip = compiler_new_block(c);
4045 if_cleanup = compiler_new_block(c);
4046 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4049 anchor == NULL)
4050 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 if (gen_index == 0) {
4055 /* Receive outermost iter as an implicit argument */
4056 c->u->u_argcount = 1;
4057 ADDOP_I(c, LOAD_FAST, 0);
4058 }
4059 else {
4060 /* Sub-iter - calculate on the fly */
4061 VISIT(c, expr, gen->iter);
4062 ADDOP(c, GET_ITER);
4063 }
4064 compiler_use_next_block(c, start);
4065 ADDOP_JREL(c, FOR_ITER, anchor);
4066 NEXT_BLOCK(c);
4067 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* XXX this needs to be cleaned up...a lot! */
4070 n = asdl_seq_LEN(gen->ifs);
4071 for (i = 0; i < n; i++) {
4072 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004073 if (!compiler_jump_if(c, e, if_cleanup, 0))
4074 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 NEXT_BLOCK(c);
4076 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 if (++gen_index < asdl_seq_LEN(generators))
4079 if (!compiler_comprehension_generator(c,
4080 generators, gen_index,
4081 elt, val, type))
4082 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 /* only append after the last for generator */
4085 if (gen_index >= asdl_seq_LEN(generators)) {
4086 /* comprehension specific code */
4087 switch (type) {
4088 case COMP_GENEXP:
4089 VISIT(c, expr, elt);
4090 ADDOP(c, YIELD_VALUE);
4091 ADDOP(c, POP_TOP);
4092 break;
4093 case COMP_LISTCOMP:
4094 VISIT(c, expr, elt);
4095 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4096 break;
4097 case COMP_SETCOMP:
4098 VISIT(c, expr, elt);
4099 ADDOP_I(c, SET_ADD, gen_index + 1);
4100 break;
4101 case COMP_DICTCOMP:
4102 /* With 'd[k] = v', v is evaluated before k, so we do
4103 the same. */
4104 VISIT(c, expr, val);
4105 VISIT(c, expr, elt);
4106 ADDOP_I(c, MAP_ADD, gen_index + 1);
4107 break;
4108 default:
4109 return 0;
4110 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 compiler_use_next_block(c, skip);
4113 }
4114 compiler_use_next_block(c, if_cleanup);
4115 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4116 compiler_use_next_block(c, anchor);
4117
4118 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119}
4120
4121static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004122compiler_async_comprehension_generator(struct compiler *c,
4123 asdl_seq *generators, int gen_index,
4124 expr_ty elt, expr_ty val, int type)
4125{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004126 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004127 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004128 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004129 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004130 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004131 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004132
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004133 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004134 return 0;
4135 }
4136
4137 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4138
4139 if (gen_index == 0) {
4140 /* Receive outermost iter as an implicit argument */
4141 c->u->u_argcount = 1;
4142 ADDOP_I(c, LOAD_FAST, 0);
4143 }
4144 else {
4145 /* Sub-iter - calculate on the fly */
4146 VISIT(c, expr, gen->iter);
4147 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004148 }
4149
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004150 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004151
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004152 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004153 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004154 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004155 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004156 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004157 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004158
4159 n = asdl_seq_LEN(gen->ifs);
4160 for (i = 0; i < n; i++) {
4161 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004162 if (!compiler_jump_if(c, e, if_cleanup, 0))
4163 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004164 NEXT_BLOCK(c);
4165 }
4166
4167 if (++gen_index < asdl_seq_LEN(generators))
4168 if (!compiler_comprehension_generator(c,
4169 generators, gen_index,
4170 elt, val, type))
4171 return 0;
4172
4173 /* only append after the last for generator */
4174 if (gen_index >= asdl_seq_LEN(generators)) {
4175 /* comprehension specific code */
4176 switch (type) {
4177 case COMP_GENEXP:
4178 VISIT(c, expr, elt);
4179 ADDOP(c, YIELD_VALUE);
4180 ADDOP(c, POP_TOP);
4181 break;
4182 case COMP_LISTCOMP:
4183 VISIT(c, expr, elt);
4184 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4185 break;
4186 case COMP_SETCOMP:
4187 VISIT(c, expr, elt);
4188 ADDOP_I(c, SET_ADD, gen_index + 1);
4189 break;
4190 case COMP_DICTCOMP:
4191 /* With 'd[k] = v', v is evaluated before k, so we do
4192 the same. */
4193 VISIT(c, expr, val);
4194 VISIT(c, expr, elt);
4195 ADDOP_I(c, MAP_ADD, gen_index + 1);
4196 break;
4197 default:
4198 return 0;
4199 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004200 }
4201 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004202 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4203
4204 compiler_use_next_block(c, except);
4205 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004206
4207 return 1;
4208}
4209
4210static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004211compiler_comprehension(struct compiler *c, expr_ty e, int type,
4212 identifier name, asdl_seq *generators, expr_ty elt,
4213 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004216 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004217 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004218 int is_async_function = c->u->u_ste->ste_coroutine;
4219 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004220
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004221 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004222
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004223 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4224 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004225 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004227 }
4228
4229 is_async_generator = c->u->u_ste->ste_coroutine;
4230
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004231 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004232 compiler_error(c, "asynchronous comprehension outside of "
4233 "an asynchronous function");
4234 goto error_in_scope;
4235 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 if (type != COMP_GENEXP) {
4238 int op;
4239 switch (type) {
4240 case COMP_LISTCOMP:
4241 op = BUILD_LIST;
4242 break;
4243 case COMP_SETCOMP:
4244 op = BUILD_SET;
4245 break;
4246 case COMP_DICTCOMP:
4247 op = BUILD_MAP;
4248 break;
4249 default:
4250 PyErr_Format(PyExc_SystemError,
4251 "unknown comprehension type %d", type);
4252 goto error_in_scope;
4253 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 ADDOP_I(c, op, 0);
4256 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 if (!compiler_comprehension_generator(c, generators, 0, elt,
4259 val, type))
4260 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (type != COMP_GENEXP) {
4263 ADDOP(c, RETURN_VALUE);
4264 }
4265
4266 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004267 qualname = c->u->u_qualname;
4268 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004270 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 goto error;
4272
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004273 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004275 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 Py_DECREF(co);
4277
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004278 VISIT(c, expr, outermost->iter);
4279
4280 if (outermost->is_async) {
4281 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004282 } else {
4283 ADDOP(c, GET_ITER);
4284 }
4285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004287
4288 if (is_async_generator && type != COMP_GENEXP) {
4289 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004290 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004291 ADDOP(c, YIELD_FROM);
4292 }
4293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004295error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004297error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004298 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 Py_XDECREF(co);
4300 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004301}
4302
4303static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004304compiler_genexp(struct compiler *c, expr_ty e)
4305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 static identifier name;
4307 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004308 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 if (!name)
4310 return 0;
4311 }
4312 assert(e->kind == GeneratorExp_kind);
4313 return compiler_comprehension(c, e, COMP_GENEXP, name,
4314 e->v.GeneratorExp.generators,
4315 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316}
4317
4318static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004319compiler_listcomp(struct compiler *c, expr_ty e)
4320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 static identifier name;
4322 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004323 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 if (!name)
4325 return 0;
4326 }
4327 assert(e->kind == ListComp_kind);
4328 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4329 e->v.ListComp.generators,
4330 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004331}
4332
4333static int
4334compiler_setcomp(struct compiler *c, expr_ty e)
4335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 static identifier name;
4337 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004338 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 if (!name)
4340 return 0;
4341 }
4342 assert(e->kind == SetComp_kind);
4343 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4344 e->v.SetComp.generators,
4345 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004346}
4347
4348
4349static int
4350compiler_dictcomp(struct compiler *c, expr_ty e)
4351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 static identifier name;
4353 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004354 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (!name)
4356 return 0;
4357 }
4358 assert(e->kind == DictComp_kind);
4359 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4360 e->v.DictComp.generators,
4361 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004362}
4363
4364
4365static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366compiler_visit_keyword(struct compiler *c, keyword_ty k)
4367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 VISIT(c, expr, k->value);
4369 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370}
4371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373 whether they are true or false.
4374
4375 Return values: 1 for true, 0 for false, -1 for non-constant.
4376 */
4377
4378static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004379expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004381 if (e->kind == Constant_kind) {
4382 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004383 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004384 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385}
4386
Yury Selivanov75445082015-05-11 22:57:16 -04004387
4388/*
4389 Implements the async with statement.
4390
4391 The semantics outlined in that PEP are as follows:
4392
4393 async with EXPR as VAR:
4394 BLOCK
4395
4396 It is implemented roughly as:
4397
4398 context = EXPR
4399 exit = context.__aexit__ # not calling it
4400 value = await context.__aenter__()
4401 try:
4402 VAR = value # if VAR present in the syntax
4403 BLOCK
4404 finally:
4405 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004406 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004407 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004408 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004409 if not (await exit(*exc)):
4410 raise
4411 */
4412static int
4413compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4414{
4415 basicblock *block, *finally;
4416 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4417
4418 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004419 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4420 return compiler_error(c, "'async with' outside async function");
4421 }
Yury Selivanov75445082015-05-11 22:57:16 -04004422
4423 block = compiler_new_block(c);
4424 finally = compiler_new_block(c);
4425 if (!block || !finally)
4426 return 0;
4427
4428 /* Evaluate EXPR */
4429 VISIT(c, expr, item->context_expr);
4430
4431 ADDOP(c, BEFORE_ASYNC_WITH);
4432 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004433 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004434 ADDOP(c, YIELD_FROM);
4435
4436 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4437
4438 /* SETUP_ASYNC_WITH pushes a finally block. */
4439 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004440 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004441 return 0;
4442 }
4443
4444 if (item->optional_vars) {
4445 VISIT(c, expr, item->optional_vars);
4446 }
4447 else {
4448 /* Discard result from context.__aenter__() */
4449 ADDOP(c, POP_TOP);
4450 }
4451
4452 pos++;
4453 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4454 /* BLOCK code */
4455 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4456 else if (!compiler_async_with(c, s, pos))
4457 return 0;
4458
4459 /* End of try block; start the finally block */
4460 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004461 ADDOP(c, BEGIN_FINALLY);
4462 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004463
Yury Selivanov75445082015-05-11 22:57:16 -04004464 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004465 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004466 return 0;
4467
4468 /* Finally block starts; context.__exit__ is on the stack under
4469 the exception or return information. Just issue our magic
4470 opcode. */
4471 ADDOP(c, WITH_CLEANUP_START);
4472
4473 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004474 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004475 ADDOP(c, YIELD_FROM);
4476
4477 ADDOP(c, WITH_CLEANUP_FINISH);
4478
4479 /* Finally block ends. */
4480 ADDOP(c, END_FINALLY);
4481 compiler_pop_fblock(c, FINALLY_END, finally);
4482 return 1;
4483}
4484
4485
Guido van Rossumc2e20742006-02-27 22:32:47 +00004486/*
4487 Implements the with statement from PEP 343.
4488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004490
4491 with EXPR as VAR:
4492 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493
Guido van Rossumc2e20742006-02-27 22:32:47 +00004494 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495
Thomas Wouters477c8d52006-05-27 19:21:47 +00004496 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004497 exit = context.__exit__ # not calling it
4498 value = context.__enter__()
4499 try:
4500 VAR = value # if VAR present in the syntax
4501 BLOCK
4502 finally:
4503 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004504 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004505 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004506 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004507 exit(*exc)
4508 */
4509static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004510compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004511{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004512 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004513 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004514
4515 assert(s->kind == With_kind);
4516
Guido van Rossumc2e20742006-02-27 22:32:47 +00004517 block = compiler_new_block(c);
4518 finally = compiler_new_block(c);
4519 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004520 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004521
Thomas Wouters477c8d52006-05-27 19:21:47 +00004522 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004523 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004524 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004525
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004526 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004527 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004528 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004529 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004530 }
4531
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004532 if (item->optional_vars) {
4533 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004534 }
4535 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004537 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004538 }
4539
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004540 pos++;
4541 if (pos == asdl_seq_LEN(s->v.With.items))
4542 /* BLOCK code */
4543 VISIT_SEQ(c, stmt, s->v.With.body)
4544 else if (!compiler_with(c, s, pos))
4545 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004546
4547 /* End of try block; start the finally block */
4548 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004549 ADDOP(c, BEGIN_FINALLY);
4550 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004551
Guido van Rossumc2e20742006-02-27 22:32:47 +00004552 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004553 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004554 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004555
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004556 /* Finally block starts; context.__exit__ is on the stack under
4557 the exception or return information. Just issue our magic
4558 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004559 ADDOP(c, WITH_CLEANUP_START);
4560 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004561
4562 /* Finally block ends. */
4563 ADDOP(c, END_FINALLY);
4564 compiler_pop_fblock(c, FINALLY_END, finally);
4565 return 1;
4566}
4567
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004568static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004569compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 switch (e->kind) {
4572 case BoolOp_kind:
4573 return compiler_boolop(c, e);
4574 case BinOp_kind:
4575 VISIT(c, expr, e->v.BinOp.left);
4576 VISIT(c, expr, e->v.BinOp.right);
4577 ADDOP(c, binop(c, e->v.BinOp.op));
4578 break;
4579 case UnaryOp_kind:
4580 VISIT(c, expr, e->v.UnaryOp.operand);
4581 ADDOP(c, unaryop(e->v.UnaryOp.op));
4582 break;
4583 case Lambda_kind:
4584 return compiler_lambda(c, e);
4585 case IfExp_kind:
4586 return compiler_ifexp(c, e);
4587 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004588 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004590 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 case GeneratorExp_kind:
4592 return compiler_genexp(c, e);
4593 case ListComp_kind:
4594 return compiler_listcomp(c, e);
4595 case SetComp_kind:
4596 return compiler_setcomp(c, e);
4597 case DictComp_kind:
4598 return compiler_dictcomp(c, e);
4599 case Yield_kind:
4600 if (c->u->u_ste->ste_type != FunctionBlock)
4601 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004602 if (e->v.Yield.value) {
4603 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 }
4605 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004606 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004608 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004610 case YieldFrom_kind:
4611 if (c->u->u_ste->ste_type != FunctionBlock)
4612 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004613
4614 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4615 return compiler_error(c, "'yield from' inside async function");
4616
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004617 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004618 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004619 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004620 ADDOP(c, YIELD_FROM);
4621 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004622 case Await_kind:
4623 if (c->u->u_ste->ste_type != FunctionBlock)
4624 return compiler_error(c, "'await' outside function");
4625
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004626 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4627 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004628 return compiler_error(c, "'await' outside async function");
4629
4630 VISIT(c, expr, e->v.Await.value);
4631 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004632 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004633 ADDOP(c, YIELD_FROM);
4634 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 case Compare_kind:
4636 return compiler_compare(c, e);
4637 case Call_kind:
4638 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004639 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004640 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004641 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004642 case JoinedStr_kind:
4643 return compiler_joined_str(c, e);
4644 case FormattedValue_kind:
4645 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 /* The following exprs can be assignment targets. */
4647 case Attribute_kind:
4648 if (e->v.Attribute.ctx != AugStore)
4649 VISIT(c, expr, e->v.Attribute.value);
4650 switch (e->v.Attribute.ctx) {
4651 case AugLoad:
4652 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004653 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 case Load:
4655 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4656 break;
4657 case AugStore:
4658 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004659 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 case Store:
4661 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4662 break;
4663 case Del:
4664 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4665 break;
4666 case Param:
4667 default:
4668 PyErr_SetString(PyExc_SystemError,
4669 "param invalid in attribute expression");
4670 return 0;
4671 }
4672 break;
4673 case Subscript_kind:
4674 switch (e->v.Subscript.ctx) {
4675 case AugLoad:
4676 VISIT(c, expr, e->v.Subscript.value);
4677 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4678 break;
4679 case Load:
4680 VISIT(c, expr, e->v.Subscript.value);
4681 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4682 break;
4683 case AugStore:
4684 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4685 break;
4686 case Store:
4687 VISIT(c, expr, e->v.Subscript.value);
4688 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4689 break;
4690 case Del:
4691 VISIT(c, expr, e->v.Subscript.value);
4692 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4693 break;
4694 case Param:
4695 default:
4696 PyErr_SetString(PyExc_SystemError,
4697 "param invalid in subscript expression");
4698 return 0;
4699 }
4700 break;
4701 case Starred_kind:
4702 switch (e->v.Starred.ctx) {
4703 case Store:
4704 /* In all legitimate cases, the Starred node was already replaced
4705 * by compiler_list/compiler_tuple. XXX: is that okay? */
4706 return compiler_error(c,
4707 "starred assignment target must be in a list or tuple");
4708 default:
4709 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004710 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 }
4712 break;
4713 case Name_kind:
4714 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4715 /* child nodes of List and Tuple will have expr_context set */
4716 case List_kind:
4717 return compiler_list(c, e);
4718 case Tuple_kind:
4719 return compiler_tuple(c, e);
4720 }
4721 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004722}
4723
4724static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004725compiler_visit_expr(struct compiler *c, expr_ty e)
4726{
4727 /* If expr e has a different line number than the last expr/stmt,
4728 set a new line number for the next instruction.
4729 */
4730 int old_lineno = c->u->u_lineno;
4731 int old_col_offset = c->u->u_col_offset;
4732 if (e->lineno != c->u->u_lineno) {
4733 c->u->u_lineno = e->lineno;
4734 c->u->u_lineno_set = 0;
4735 }
4736 /* Updating the column offset is always harmless. */
4737 c->u->u_col_offset = e->col_offset;
4738
4739 int res = compiler_visit_expr1(c, e);
4740
4741 if (old_lineno != c->u->u_lineno) {
4742 c->u->u_lineno = old_lineno;
4743 c->u->u_lineno_set = 0;
4744 }
4745 c->u->u_col_offset = old_col_offset;
4746 return res;
4747}
4748
4749static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004750compiler_augassign(struct compiler *c, stmt_ty s)
4751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 expr_ty e = s->v.AugAssign.target;
4753 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 switch (e->kind) {
4758 case Attribute_kind:
4759 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004760 AugLoad, e->lineno, e->col_offset,
4761 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (auge == NULL)
4763 return 0;
4764 VISIT(c, expr, auge);
4765 VISIT(c, expr, s->v.AugAssign.value);
4766 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4767 auge->v.Attribute.ctx = AugStore;
4768 VISIT(c, expr, auge);
4769 break;
4770 case Subscript_kind:
4771 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004772 AugLoad, e->lineno, e->col_offset,
4773 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 if (auge == NULL)
4775 return 0;
4776 VISIT(c, expr, auge);
4777 VISIT(c, expr, s->v.AugAssign.value);
4778 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4779 auge->v.Subscript.ctx = AugStore;
4780 VISIT(c, expr, auge);
4781 break;
4782 case Name_kind:
4783 if (!compiler_nameop(c, e->v.Name.id, Load))
4784 return 0;
4785 VISIT(c, expr, s->v.AugAssign.value);
4786 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4787 return compiler_nameop(c, e->v.Name.id, Store);
4788 default:
4789 PyErr_Format(PyExc_SystemError,
4790 "invalid node type (%d) for augmented assignment",
4791 e->kind);
4792 return 0;
4793 }
4794 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004795}
4796
4797static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004798check_ann_expr(struct compiler *c, expr_ty e)
4799{
4800 VISIT(c, expr, e);
4801 ADDOP(c, POP_TOP);
4802 return 1;
4803}
4804
4805static int
4806check_annotation(struct compiler *c, stmt_ty s)
4807{
4808 /* Annotations are only evaluated in a module or class. */
4809 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4810 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4811 return check_ann_expr(c, s->v.AnnAssign.annotation);
4812 }
4813 return 1;
4814}
4815
4816static int
4817check_ann_slice(struct compiler *c, slice_ty sl)
4818{
4819 switch(sl->kind) {
4820 case Index_kind:
4821 return check_ann_expr(c, sl->v.Index.value);
4822 case Slice_kind:
4823 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4824 return 0;
4825 }
4826 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4827 return 0;
4828 }
4829 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4830 return 0;
4831 }
4832 break;
4833 default:
4834 PyErr_SetString(PyExc_SystemError,
4835 "unexpected slice kind");
4836 return 0;
4837 }
4838 return 1;
4839}
4840
4841static int
4842check_ann_subscr(struct compiler *c, slice_ty sl)
4843{
4844 /* We check that everything in a subscript is defined at runtime. */
4845 Py_ssize_t i, n;
4846
4847 switch (sl->kind) {
4848 case Index_kind:
4849 case Slice_kind:
4850 if (!check_ann_slice(c, sl)) {
4851 return 0;
4852 }
4853 break;
4854 case ExtSlice_kind:
4855 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4856 for (i = 0; i < n; i++) {
4857 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4858 switch (subsl->kind) {
4859 case Index_kind:
4860 case Slice_kind:
4861 if (!check_ann_slice(c, subsl)) {
4862 return 0;
4863 }
4864 break;
4865 case ExtSlice_kind:
4866 default:
4867 PyErr_SetString(PyExc_SystemError,
4868 "extended slice invalid in nested slice");
4869 return 0;
4870 }
4871 }
4872 break;
4873 default:
4874 PyErr_Format(PyExc_SystemError,
4875 "invalid subscript kind %d", sl->kind);
4876 return 0;
4877 }
4878 return 1;
4879}
4880
4881static int
4882compiler_annassign(struct compiler *c, stmt_ty s)
4883{
4884 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004885 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004886
4887 assert(s->kind == AnnAssign_kind);
4888
4889 /* We perform the actual assignment first. */
4890 if (s->v.AnnAssign.value) {
4891 VISIT(c, expr, s->v.AnnAssign.value);
4892 VISIT(c, expr, targ);
4893 }
4894 switch (targ->kind) {
4895 case Name_kind:
4896 /* If we have a simple name in a module or class, store annotation. */
4897 if (s->v.AnnAssign.simple &&
4898 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4899 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004900 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4901 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4902 }
4903 else {
4904 VISIT(c, expr, s->v.AnnAssign.annotation);
4905 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004906 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004907 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004908 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004909 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004910 }
4911 break;
4912 case Attribute_kind:
4913 if (!s->v.AnnAssign.value &&
4914 !check_ann_expr(c, targ->v.Attribute.value)) {
4915 return 0;
4916 }
4917 break;
4918 case Subscript_kind:
4919 if (!s->v.AnnAssign.value &&
4920 (!check_ann_expr(c, targ->v.Subscript.value) ||
4921 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4922 return 0;
4923 }
4924 break;
4925 default:
4926 PyErr_Format(PyExc_SystemError,
4927 "invalid node type (%d) for annotated assignment",
4928 targ->kind);
4929 return 0;
4930 }
4931 /* Annotation is evaluated last. */
4932 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4933 return 0;
4934 }
4935 return 1;
4936}
4937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004938/* Raises a SyntaxError and returns 0.
4939 If something goes wrong, a different exception may be raised.
4940*/
4941
4942static int
4943compiler_error(struct compiler *c, const char *errstr)
4944{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004945 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004947
Victor Stinner14e461d2013-08-26 22:28:21 +02004948 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 if (!loc) {
4950 Py_INCREF(Py_None);
4951 loc = Py_None;
4952 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004953 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004954 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 if (!u)
4956 goto exit;
4957 v = Py_BuildValue("(zO)", errstr, u);
4958 if (!v)
4959 goto exit;
4960 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004961 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 Py_DECREF(loc);
4963 Py_XDECREF(u);
4964 Py_XDECREF(v);
4965 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966}
4967
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004968/* Emits a SyntaxWarning and returns 1 on success.
4969 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4970 and returns 0.
4971*/
4972static int
4973compiler_warn(struct compiler *c, const char *errstr)
4974{
4975 PyObject *msg = PyUnicode_FromString(errstr);
4976 if (msg == NULL) {
4977 return 0;
4978 }
4979 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4980 c->u->u_lineno, NULL, NULL) < 0)
4981 {
4982 Py_DECREF(msg);
4983 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4984 PyErr_Clear();
4985 return compiler_error(c, errstr);
4986 }
4987 return 0;
4988 }
4989 Py_DECREF(msg);
4990 return 1;
4991}
4992
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004993static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994compiler_handle_subscr(struct compiler *c, const char *kind,
4995 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 /* XXX this code is duplicated */
5000 switch (ctx) {
5001 case AugLoad: /* fall through to Load */
5002 case Load: op = BINARY_SUBSCR; break;
5003 case AugStore:/* fall through to Store */
5004 case Store: op = STORE_SUBSCR; break;
5005 case Del: op = DELETE_SUBSCR; break;
5006 case Param:
5007 PyErr_Format(PyExc_SystemError,
5008 "invalid %s kind %d in subscript\n",
5009 kind, ctx);
5010 return 0;
5011 }
5012 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005013 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 }
5015 else if (ctx == AugStore) {
5016 ADDOP(c, ROT_THREE);
5017 }
5018 ADDOP(c, op);
5019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005020}
5021
5022static int
5023compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 int n = 2;
5026 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 /* only handles the cases where BUILD_SLICE is emitted */
5029 if (s->v.Slice.lower) {
5030 VISIT(c, expr, s->v.Slice.lower);
5031 }
5032 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005033 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 if (s->v.Slice.upper) {
5037 VISIT(c, expr, s->v.Slice.upper);
5038 }
5039 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005040 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 }
5042
5043 if (s->v.Slice.step) {
5044 n++;
5045 VISIT(c, expr, s->v.Slice.step);
5046 }
5047 ADDOP_I(c, BUILD_SLICE, n);
5048 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005049}
5050
5051static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5053 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 switch (s->kind) {
5056 case Slice_kind:
5057 return compiler_slice(c, s, ctx);
5058 case Index_kind:
5059 VISIT(c, expr, s->v.Index.value);
5060 break;
5061 case ExtSlice_kind:
5062 default:
5063 PyErr_SetString(PyExc_SystemError,
5064 "extended slice invalid in nested slice");
5065 return 0;
5066 }
5067 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005068}
5069
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005070static int
5071compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5072{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005073 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 switch (s->kind) {
5075 case Index_kind:
5076 kindname = "index";
5077 if (ctx != AugStore) {
5078 VISIT(c, expr, s->v.Index.value);
5079 }
5080 break;
5081 case Slice_kind:
5082 kindname = "slice";
5083 if (ctx != AugStore) {
5084 if (!compiler_slice(c, s, ctx))
5085 return 0;
5086 }
5087 break;
5088 case ExtSlice_kind:
5089 kindname = "extended slice";
5090 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005091 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 for (i = 0; i < n; i++) {
5093 slice_ty sub = (slice_ty)asdl_seq_GET(
5094 s->v.ExtSlice.dims, i);
5095 if (!compiler_visit_nested_slice(c, sub, ctx))
5096 return 0;
5097 }
5098 ADDOP_I(c, BUILD_TUPLE, n);
5099 }
5100 break;
5101 default:
5102 PyErr_Format(PyExc_SystemError,
5103 "invalid subscript kind %d", s->kind);
5104 return 0;
5105 }
5106 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107}
5108
Thomas Wouters89f507f2006-12-13 04:49:30 +00005109/* End of the compiler section, beginning of the assembler section */
5110
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111/* do depth-first search of basic block graph, starting with block.
5112 post records the block indices in post-order.
5113
5114 XXX must handle implicit jumps from one block to next
5115*/
5116
Thomas Wouters89f507f2006-12-13 04:49:30 +00005117struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 PyObject *a_bytecode; /* string containing bytecode */
5119 int a_offset; /* offset into bytecode */
5120 int a_nblocks; /* number of reachable blocks */
5121 basicblock **a_postorder; /* list of blocks in dfs postorder */
5122 PyObject *a_lnotab; /* string containing lnotab */
5123 int a_lnotab_off; /* offset into lnotab */
5124 int a_lineno; /* last lineno of emitted instruction */
5125 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005126};
5127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005128static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005129dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005130{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005131 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005132
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005133 /* Get rid of recursion for normal control flow.
5134 Since the number of blocks is limited, unused space in a_postorder
5135 (from a_nblocks to end) can be used as a stack for still not ordered
5136 blocks. */
5137 for (j = end; b && !b->b_seen; b = b->b_next) {
5138 b->b_seen = 1;
5139 assert(a->a_nblocks < j);
5140 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005142 while (j < end) {
5143 b = a->a_postorder[j++];
5144 for (i = 0; i < b->b_iused; i++) {
5145 struct instr *instr = &b->b_instr[i];
5146 if (instr->i_jrel || instr->i_jabs)
5147 dfs(c, instr->i_target, a, j);
5148 }
5149 assert(a->a_nblocks < j);
5150 a->a_postorder[a->a_nblocks++] = b;
5151 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005152}
5153
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005154Py_LOCAL_INLINE(void)
5155stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005156{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005157 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005158 if (b->b_startdepth < depth) {
5159 assert(b->b_startdepth < 0);
5160 b->b_startdepth = depth;
5161 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005163}
5164
5165/* Find the flow path that needs the largest stack. We assume that
5166 * cycles in the flow graph have no net effect on the stack depth.
5167 */
5168static int
5169stackdepth(struct compiler *c)
5170{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005171 basicblock *b, *entryblock = NULL;
5172 basicblock **stack, **sp;
5173 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 b->b_startdepth = INT_MIN;
5176 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005177 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 }
5179 if (!entryblock)
5180 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005181 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5182 if (!stack) {
5183 PyErr_NoMemory();
5184 return -1;
5185 }
5186
5187 sp = stack;
5188 stackdepth_push(&sp, entryblock, 0);
5189 while (sp != stack) {
5190 b = *--sp;
5191 int depth = b->b_startdepth;
5192 assert(depth >= 0);
5193 basicblock *next = b->b_next;
5194 for (int i = 0; i < b->b_iused; i++) {
5195 struct instr *instr = &b->b_instr[i];
5196 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5197 if (effect == PY_INVALID_STACK_EFFECT) {
5198 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5199 Py_FatalError("PyCompile_OpcodeStackEffect()");
5200 }
5201 int new_depth = depth + effect;
5202 if (new_depth > maxdepth) {
5203 maxdepth = new_depth;
5204 }
5205 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5206 if (instr->i_jrel || instr->i_jabs) {
5207 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5208 assert(effect != PY_INVALID_STACK_EFFECT);
5209 int target_depth = depth + effect;
5210 if (target_depth > maxdepth) {
5211 maxdepth = target_depth;
5212 }
5213 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005214 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005215 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005216 assert(instr->i_target->b_startdepth >= target_depth);
5217 depth = new_depth;
5218 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005219 }
5220 stackdepth_push(&sp, instr->i_target, target_depth);
5221 }
5222 depth = new_depth;
5223 if (instr->i_opcode == JUMP_ABSOLUTE ||
5224 instr->i_opcode == JUMP_FORWARD ||
5225 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005226 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005227 {
5228 /* remaining code is dead */
5229 next = NULL;
5230 break;
5231 }
5232 }
5233 if (next != NULL) {
5234 stackdepth_push(&sp, next, depth);
5235 }
5236 }
5237 PyObject_Free(stack);
5238 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005239}
5240
5241static int
5242assemble_init(struct assembler *a, int nblocks, int firstlineno)
5243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 memset(a, 0, sizeof(struct assembler));
5245 a->a_lineno = firstlineno;
5246 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5247 if (!a->a_bytecode)
5248 return 0;
5249 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5250 if (!a->a_lnotab)
5251 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005252 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 PyErr_NoMemory();
5254 return 0;
5255 }
5256 a->a_postorder = (basicblock **)PyObject_Malloc(
5257 sizeof(basicblock *) * nblocks);
5258 if (!a->a_postorder) {
5259 PyErr_NoMemory();
5260 return 0;
5261 }
5262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005263}
5264
5265static void
5266assemble_free(struct assembler *a)
5267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 Py_XDECREF(a->a_bytecode);
5269 Py_XDECREF(a->a_lnotab);
5270 if (a->a_postorder)
5271 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005272}
5273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005274static int
5275blocksize(basicblock *b)
5276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 int i;
5278 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005281 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005283}
5284
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005285/* Appends a pair to the end of the line number table, a_lnotab, representing
5286 the instruction's bytecode offset and line number. See
5287 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005288
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005289static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005293 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295
Serhiy Storchakaab874002016-09-11 13:48:15 +03005296 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if(d_bytecode == 0 && d_lineno == 0)
5302 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 if (d_bytecode > 255) {
5305 int j, nbytes, ncodes = d_bytecode / 255;
5306 nbytes = a->a_lnotab_off + 2 * ncodes;
5307 len = PyBytes_GET_SIZE(a->a_lnotab);
5308 if (nbytes >= len) {
5309 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5310 len = nbytes;
5311 else if (len <= INT_MAX / 2)
5312 len *= 2;
5313 else {
5314 PyErr_NoMemory();
5315 return 0;
5316 }
5317 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5318 return 0;
5319 }
5320 lnotab = (unsigned char *)
5321 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5322 for (j = 0; j < ncodes; j++) {
5323 *lnotab++ = 255;
5324 *lnotab++ = 0;
5325 }
5326 d_bytecode -= ncodes * 255;
5327 a->a_lnotab_off += ncodes * 2;
5328 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005329 assert(0 <= d_bytecode && d_bytecode <= 255);
5330
5331 if (d_lineno < -128 || 127 < d_lineno) {
5332 int j, nbytes, ncodes, k;
5333 if (d_lineno < 0) {
5334 k = -128;
5335 /* use division on positive numbers */
5336 ncodes = (-d_lineno) / 128;
5337 }
5338 else {
5339 k = 127;
5340 ncodes = d_lineno / 127;
5341 }
5342 d_lineno -= ncodes * k;
5343 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 nbytes = a->a_lnotab_off + 2 * ncodes;
5345 len = PyBytes_GET_SIZE(a->a_lnotab);
5346 if (nbytes >= len) {
5347 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5348 len = nbytes;
5349 else if (len <= INT_MAX / 2)
5350 len *= 2;
5351 else {
5352 PyErr_NoMemory();
5353 return 0;
5354 }
5355 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5356 return 0;
5357 }
5358 lnotab = (unsigned char *)
5359 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5360 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005361 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 d_bytecode = 0;
5363 for (j = 1; j < ncodes; j++) {
5364 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005365 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 a->a_lnotab_off += ncodes * 2;
5368 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005369 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 len = PyBytes_GET_SIZE(a->a_lnotab);
5372 if (a->a_lnotab_off + 2 >= len) {
5373 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5374 return 0;
5375 }
5376 lnotab = (unsigned char *)
5377 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 a->a_lnotab_off += 2;
5380 if (d_bytecode) {
5381 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005382 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 }
5384 else { /* First line of a block; def stmt, etc. */
5385 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005386 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 }
5388 a->a_lineno = i->i_lineno;
5389 a->a_lineno_off = a->a_offset;
5390 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005391}
5392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005393/* assemble_emit()
5394 Extend the bytecode with a new instruction.
5395 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005396*/
5397
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005398static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005399assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005400{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005401 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005403 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005405 arg = i->i_oparg;
5406 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 if (i->i_lineno && !assemble_lnotab(a, i))
5408 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005409 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 if (len > PY_SSIZE_T_MAX / 2)
5411 return 0;
5412 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5413 return 0;
5414 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005415 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005417 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005419}
5420
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005421static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005422assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005425 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 /* Compute the size of each block and fixup jump args.
5429 Replace block pointer with position in bytecode. */
5430 do {
5431 totsize = 0;
5432 for (i = a->a_nblocks - 1; i >= 0; i--) {
5433 b = a->a_postorder[i];
5434 bsize = blocksize(b);
5435 b->b_offset = totsize;
5436 totsize += bsize;
5437 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005438 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5440 bsize = b->b_offset;
5441 for (i = 0; i < b->b_iused; i++) {
5442 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005443 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 /* Relative jumps are computed relative to
5445 the instruction pointer after fetching
5446 the jump instruction.
5447 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005448 bsize += isize;
5449 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005451 if (instr->i_jrel) {
5452 instr->i_oparg -= bsize;
5453 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005454 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005455 if (instrsize(instr->i_oparg) != isize) {
5456 extended_arg_recompile = 1;
5457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 }
5460 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 /* XXX: This is an awful hack that could hurt performance, but
5463 on the bright side it should work until we come up
5464 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 The issue is that in the first loop blocksize() is called
5467 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005468 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 So we loop until we stop seeing new EXTENDED_ARGs.
5472 The only EXTENDED_ARGs that could be popping up are
5473 ones in jump instructions. So this should converge
5474 fairly quickly.
5475 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005476 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005477}
5478
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005479static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005480dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005483 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 tuple = PyTuple_New(size);
5486 if (tuple == NULL)
5487 return NULL;
5488 while (PyDict_Next(dict, &pos, &k, &v)) {
5489 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005490 Py_INCREF(k);
5491 assert((i - offset) < size);
5492 assert((i - offset) >= 0);
5493 PyTuple_SET_ITEM(tuple, i - offset, k);
5494 }
5495 return tuple;
5496}
5497
5498static PyObject *
5499consts_dict_keys_inorder(PyObject *dict)
5500{
5501 PyObject *consts, *k, *v;
5502 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5503
5504 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5505 if (consts == NULL)
5506 return NULL;
5507 while (PyDict_Next(dict, &pos, &k, &v)) {
5508 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005509 /* The keys of the dictionary can be tuples wrapping a contant.
5510 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5511 * the object we want is always second. */
5512 if (PyTuple_CheckExact(k)) {
5513 k = PyTuple_GET_ITEM(k, 1);
5514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005516 assert(i < size);
5517 assert(i >= 0);
5518 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005520 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005521}
5522
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005523static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005524compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005527 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005529 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 if (ste->ste_nested)
5531 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005532 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005534 if (!ste->ste_generator && ste->ste_coroutine)
5535 flags |= CO_COROUTINE;
5536 if (ste->ste_generator && ste->ste_coroutine)
5537 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 if (ste->ste_varargs)
5539 flags |= CO_VARARGS;
5540 if (ste->ste_varkeywords)
5541 flags |= CO_VARKEYWORDS;
5542 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 /* (Only) inherit compilerflags in PyCF_MASK */
5545 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005548}
5549
INADA Naokic2e16072018-11-26 21:23:22 +09005550// Merge *tuple* with constant cache.
5551// Unlike merge_consts_recursive(), this function doesn't work recursively.
5552static int
5553merge_const_tuple(struct compiler *c, PyObject **tuple)
5554{
5555 assert(PyTuple_CheckExact(*tuple));
5556
5557 PyObject *key = _PyCode_ConstantKey(*tuple);
5558 if (key == NULL) {
5559 return 0;
5560 }
5561
5562 // t is borrowed reference
5563 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5564 Py_DECREF(key);
5565 if (t == NULL) {
5566 return 0;
5567 }
5568 if (t == key) { // tuple is new constant.
5569 return 1;
5570 }
5571
5572 PyObject *u = PyTuple_GET_ITEM(t, 1);
5573 Py_INCREF(u);
5574 Py_DECREF(*tuple);
5575 *tuple = u;
5576 return 1;
5577}
5578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005579static PyCodeObject *
5580makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 PyObject *tmp;
5583 PyCodeObject *co = NULL;
5584 PyObject *consts = NULL;
5585 PyObject *names = NULL;
5586 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 PyObject *name = NULL;
5588 PyObject *freevars = NULL;
5589 PyObject *cellvars = NULL;
5590 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005591 Py_ssize_t nlocals;
5592 int nlocals_int;
5593 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005594 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005595
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005596 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 names = dict_keys_inorder(c->u->u_names, 0);
5598 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5599 if (!consts || !names || !varnames)
5600 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5603 if (!cellvars)
5604 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005605 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 if (!freevars)
5607 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005608
INADA Naokic2e16072018-11-26 21:23:22 +09005609 if (!merge_const_tuple(c, &names) ||
5610 !merge_const_tuple(c, &varnames) ||
5611 !merge_const_tuple(c, &cellvars) ||
5612 !merge_const_tuple(c, &freevars))
5613 {
5614 goto error;
5615 }
5616
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005617 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005618 assert(nlocals < INT_MAX);
5619 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 flags = compute_code_flags(c);
5622 if (flags < 0)
5623 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5626 if (!bytecode)
5627 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5630 if (!tmp)
5631 goto error;
5632 Py_DECREF(consts);
5633 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005634 if (!merge_const_tuple(c, &consts)) {
5635 goto error;
5636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637
Victor Stinnerf8e32212013-11-19 23:56:34 +01005638 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5639 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005640 maxdepth = stackdepth(c);
5641 if (maxdepth < 0) {
5642 goto error;
5643 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005644 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005645 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 bytecode, consts, names, varnames,
5647 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005648 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 c->u->u_firstlineno,
5650 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005651 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 Py_XDECREF(consts);
5653 Py_XDECREF(names);
5654 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 Py_XDECREF(name);
5656 Py_XDECREF(freevars);
5657 Py_XDECREF(cellvars);
5658 Py_XDECREF(bytecode);
5659 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005660}
5661
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005662
5663/* For debugging purposes only */
5664#if 0
5665static void
5666dump_instr(const struct instr *i)
5667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 const char *jrel = i->i_jrel ? "jrel " : "";
5669 const char *jabs = i->i_jabs ? "jabs " : "";
5670 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005673 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5677 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005678}
5679
5680static void
5681dump_basicblock(const basicblock *b)
5682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 const char *seen = b->b_seen ? "seen " : "";
5684 const char *b_return = b->b_return ? "return " : "";
5685 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5686 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5687 if (b->b_instr) {
5688 int i;
5689 for (i = 0; i < b->b_iused; i++) {
5690 fprintf(stderr, " [%02d] ", i);
5691 dump_instr(b->b_instr + i);
5692 }
5693 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005694}
5695#endif
5696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005697static PyCodeObject *
5698assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 basicblock *b, *entryblock;
5701 struct assembler a;
5702 int i, j, nblocks;
5703 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 /* Make sure every block that falls off the end returns None.
5706 XXX NEXT_BLOCK() isn't quite right, because if the last
5707 block ends with a jump or return b_next shouldn't set.
5708 */
5709 if (!c->u->u_curblock->b_return) {
5710 NEXT_BLOCK(c);
5711 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005712 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 ADDOP(c, RETURN_VALUE);
5714 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 nblocks = 0;
5717 entryblock = NULL;
5718 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5719 nblocks++;
5720 entryblock = b;
5721 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 /* Set firstlineno if it wasn't explicitly set. */
5724 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005725 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5727 else
5728 c->u->u_firstlineno = 1;
5729 }
5730 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5731 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005732 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 /* Can't modify the bytecode after computing jump offsets. */
5735 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005737 /* Emit code in reverse postorder from dfs. */
5738 for (i = a.a_nblocks - 1; i >= 0; i--) {
5739 b = a.a_postorder[i];
5740 for (j = 0; j < b->b_iused; j++)
5741 if (!assemble_emit(&a, &b->b_instr[j]))
5742 goto error;
5743 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5746 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005747 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005751 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 assemble_free(&a);
5753 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005754}
Georg Brandl8334fd92010-12-04 10:26:46 +00005755
5756#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005757PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005758PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5759 PyArena *arena)
5760{
5761 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5762}