blob: acb5cfe29b42b35faff6c33b480797d801fc2bd6 [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) {
1211 Py_INCREF(t);
1212 Py_DECREF(key);
1213 return t;
1214 }
1215
1216 if (PyTuple_CheckExact(o)) {
1217 Py_ssize_t i, len = PyTuple_GET_SIZE(o);
1218 for (i = 0; i < len; i++) {
1219 PyObject *item = PyTuple_GET_ITEM(o, i);
1220 PyObject *u = merge_consts_recursive(c, item);
1221 if (u == NULL) {
1222 Py_DECREF(key);
1223 return NULL;
1224 }
1225
1226 // See _PyCode_ConstantKey()
1227 PyObject *v; // borrowed
1228 if (PyTuple_CheckExact(u)) {
1229 v = PyTuple_GET_ITEM(u, 1);
1230 }
1231 else {
1232 v = u;
1233 }
1234 if (v != item) {
1235 Py_INCREF(v);
1236 PyTuple_SET_ITEM(o, i, v);
1237 Py_DECREF(item);
1238 }
1239
1240 Py_DECREF(u);
1241 }
1242 }
1243 else if (PyFrozenSet_CheckExact(o)) {
1244 // We register items in the frozenset, but don't rewrite
1245 // the frozenset when the item is already registered
1246 // because frozenset is rare and difficult.
1247
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) {
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 }
1277 else {
1278 u = k;
1279 }
1280 Py_INCREF(u);
1281 PyTuple_SET_ITEM(tuple, i, u);
1282 i++;
1283 }
1284
1285 PyObject *new = PyFrozenSet_New(tuple);
1286 Py_DECREF(tuple);
1287 if (new == NULL) {
1288 Py_DECREF(key);
1289 return NULL;
1290 }
1291 PyTuple_SET_ITEM(key, 1, new);
1292 }
1293
1294 return key;
1295}
1296
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001297static Py_ssize_t
1298compiler_add_const(struct compiler *c, PyObject *o)
1299{
INADA Naokic2e16072018-11-26 21:23:22 +09001300 PyObject *key = merge_consts_recursive(c, o);
1301 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001302 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001303 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001304
INADA Naokic2e16072018-11-26 21:23:22 +09001305 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1306 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308}
1309
1310static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001311compiler_addop_load_const(struct compiler *c, PyObject *o)
1312{
1313 Py_ssize_t arg = compiler_add_const(c, o);
1314 if (arg < 0)
1315 return 0;
1316 return compiler_addop_i(c, LOAD_CONST, arg);
1317}
1318
1319static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001323 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 return compiler_addop_i(c, opcode, arg);
1327}
1328
1329static int
1330compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001333 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1335 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001336 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337 arg = compiler_add_o(c, dict, mangled);
1338 Py_DECREF(mangled);
1339 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001340 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341 return compiler_addop_i(c, opcode, arg);
1342}
1343
1344/* Add an opcode with an integer argument.
1345 Returns 0 on failure, 1 on success.
1346*/
1347
1348static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001349compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 struct instr *i;
1352 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001353
Victor Stinner2ad474b2016-03-01 23:34:47 +01001354 /* oparg value is unsigned, but a signed C int is usually used to store
1355 it in the C code (like Python/ceval.c).
1356
1357 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1358
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001359 The argument of a concrete bytecode instruction is limited to 8-bit.
1360 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1361 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001362 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 off = compiler_next_instr(c, c->u->u_curblock);
1365 if (off < 0)
1366 return 0;
1367 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001368 i->i_opcode = opcode;
1369 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 compiler_set_lineno(c, off);
1371 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001372}
1373
1374static int
1375compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 struct instr *i;
1378 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001380 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 assert(b != NULL);
1382 off = compiler_next_instr(c, c->u->u_curblock);
1383 if (off < 0)
1384 return 0;
1385 i = &c->u->u_curblock->b_instr[off];
1386 i->i_opcode = opcode;
1387 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 if (absolute)
1389 i->i_jabs = 1;
1390 else
1391 i->i_jrel = 1;
1392 compiler_set_lineno(c, off);
1393 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394}
1395
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001396/* NEXT_BLOCK() creates an implicit jump from the current block
1397 to the new block.
1398
1399 The returns inside this macro make it impossible to decref objects
1400 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (compiler_next_block((C)) == NULL) \
1404 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001405}
1406
1407#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (!compiler_addop((C), (OP))) \
1409 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001412#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!compiler_addop((C), (OP))) { \
1414 compiler_exit_scope(c); \
1415 return 0; \
1416 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001417}
1418
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001419#define ADDOP_LOAD_CONST(C, O) { \
1420 if (!compiler_addop_load_const((C), (O))) \
1421 return 0; \
1422}
1423
1424/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1425#define ADDOP_LOAD_CONST_NEW(C, O) { \
1426 PyObject *__new_const = (O); \
1427 if (__new_const == NULL) { \
1428 return 0; \
1429 } \
1430 if (!compiler_addop_load_const((C), __new_const)) { \
1431 Py_DECREF(__new_const); \
1432 return 0; \
1433 } \
1434 Py_DECREF(__new_const); \
1435}
1436
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1439 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001442/* Same as ADDOP_O, but steals a reference. */
1443#define ADDOP_N(C, OP, O, TYPE) { \
1444 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1445 Py_DECREF((O)); \
1446 return 0; \
1447 } \
1448 Py_DECREF((O)); \
1449}
1450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1453 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454}
1455
1456#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop_i((C), (OP), (O))) \
1458 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459}
1460
1461#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_addop_j((C), (OP), (O), 1)) \
1463 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_j((C), (OP), (O), 0)) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1472 the ASDL name to synthesize the name of the C type and the visit function.
1473*/
1474
1475#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (!compiler_visit_ ## TYPE((C), (V))) \
1477 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478}
1479
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001480#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_visit_ ## TYPE((C), (V))) { \
1482 compiler_exit_scope(c); \
1483 return 0; \
1484 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001485}
1486
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (!compiler_visit_slice((C), (V), (CTX))) \
1489 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490}
1491
1492#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 int _i; \
1494 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1495 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1496 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1497 if (!compiler_visit_ ## TYPE((C), elt)) \
1498 return 0; \
1499 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001502#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 int _i; \
1504 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1505 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1506 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1507 if (!compiler_visit_ ## TYPE((C), elt)) { \
1508 compiler_exit_scope(c); \
1509 return 0; \
1510 } \
1511 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001512}
1513
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001514/* Search if variable annotations are present statically in a block. */
1515
1516static int
1517find_ann(asdl_seq *stmts)
1518{
1519 int i, j, res = 0;
1520 stmt_ty st;
1521
1522 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1523 st = (stmt_ty)asdl_seq_GET(stmts, i);
1524 switch (st->kind) {
1525 case AnnAssign_kind:
1526 return 1;
1527 case For_kind:
1528 res = find_ann(st->v.For.body) ||
1529 find_ann(st->v.For.orelse);
1530 break;
1531 case AsyncFor_kind:
1532 res = find_ann(st->v.AsyncFor.body) ||
1533 find_ann(st->v.AsyncFor.orelse);
1534 break;
1535 case While_kind:
1536 res = find_ann(st->v.While.body) ||
1537 find_ann(st->v.While.orelse);
1538 break;
1539 case If_kind:
1540 res = find_ann(st->v.If.body) ||
1541 find_ann(st->v.If.orelse);
1542 break;
1543 case With_kind:
1544 res = find_ann(st->v.With.body);
1545 break;
1546 case AsyncWith_kind:
1547 res = find_ann(st->v.AsyncWith.body);
1548 break;
1549 case Try_kind:
1550 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1551 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1552 st->v.Try.handlers, j);
1553 if (find_ann(handler->v.ExceptHandler.body)) {
1554 return 1;
1555 }
1556 }
1557 res = find_ann(st->v.Try.body) ||
1558 find_ann(st->v.Try.finalbody) ||
1559 find_ann(st->v.Try.orelse);
1560 break;
1561 default:
1562 res = 0;
1563 }
1564 if (res) {
1565 break;
1566 }
1567 }
1568 return res;
1569}
1570
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001571/*
1572 * Frame block handling functions
1573 */
1574
1575static int
1576compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1577 basicblock *exit)
1578{
1579 struct fblockinfo *f;
1580 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1581 PyErr_SetString(PyExc_SyntaxError,
1582 "too many statically nested blocks");
1583 return 0;
1584 }
1585 f = &c->u->u_fblock[c->u->u_nfblocks++];
1586 f->fb_type = t;
1587 f->fb_block = b;
1588 f->fb_exit = exit;
1589 return 1;
1590}
1591
1592static void
1593compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1594{
1595 struct compiler_unit *u = c->u;
1596 assert(u->u_nfblocks > 0);
1597 u->u_nfblocks--;
1598 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1599 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1600}
1601
1602/* Unwind a frame block. If preserve_tos is true, the TOS before
1603 * popping the blocks will be restored afterwards.
1604 */
1605static int
1606compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1607 int preserve_tos)
1608{
1609 switch (info->fb_type) {
1610 case WHILE_LOOP:
1611 return 1;
1612
1613 case FINALLY_END:
1614 ADDOP_I(c, POP_FINALLY, preserve_tos);
1615 return 1;
1616
1617 case FOR_LOOP:
1618 /* Pop the iterator */
1619 if (preserve_tos) {
1620 ADDOP(c, ROT_TWO);
1621 }
1622 ADDOP(c, POP_TOP);
1623 return 1;
1624
1625 case EXCEPT:
1626 ADDOP(c, POP_BLOCK);
1627 return 1;
1628
1629 case FINALLY_TRY:
1630 ADDOP(c, POP_BLOCK);
1631 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1632 return 1;
1633
1634 case WITH:
1635 case ASYNC_WITH:
1636 ADDOP(c, POP_BLOCK);
1637 if (preserve_tos) {
1638 ADDOP(c, ROT_TWO);
1639 }
1640 ADDOP(c, BEGIN_FINALLY);
1641 ADDOP(c, WITH_CLEANUP_START);
1642 if (info->fb_type == ASYNC_WITH) {
1643 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001644 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001645 ADDOP(c, YIELD_FROM);
1646 }
1647 ADDOP(c, WITH_CLEANUP_FINISH);
1648 ADDOP_I(c, POP_FINALLY, 0);
1649 return 1;
1650
1651 case HANDLER_CLEANUP:
1652 if (preserve_tos) {
1653 ADDOP(c, ROT_FOUR);
1654 }
1655 if (info->fb_exit) {
1656 ADDOP(c, POP_BLOCK);
1657 ADDOP(c, POP_EXCEPT);
1658 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1659 }
1660 else {
1661 ADDOP(c, POP_EXCEPT);
1662 }
1663 return 1;
1664 }
1665 Py_UNREACHABLE();
1666}
1667
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001668/* Compile a sequence of statements, checking for a docstring
1669 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670
1671static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001672compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001674 int i = 0;
1675 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001676 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001677
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001678 /* Set current line number to the line number of first statement.
1679 This way line number for SETUP_ANNOTATIONS will always
1680 coincide with the line number of first "real" statement in module.
1681 If body is empy, then lineno will be set later in assemble. */
1682 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1683 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001684 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001685 c->u->u_lineno = st->lineno;
1686 }
1687 /* Every annotated class and module should have __annotations__. */
1688 if (find_ann(stmts)) {
1689 ADDOP(c, SETUP_ANNOTATIONS);
1690 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001691 if (!asdl_seq_LEN(stmts))
1692 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001693 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001694 if (c->c_optimize < 2) {
1695 docstring = _PyAST_GetDocString(stmts);
1696 if (docstring) {
1697 i = 1;
1698 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1699 assert(st->kind == Expr_kind);
1700 VISIT(c, expr, st->v.Expr.value);
1701 if (!compiler_nameop(c, __doc__, Store))
1702 return 0;
1703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001705 for (; i < asdl_seq_LEN(stmts); i++)
1706 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708}
1709
1710static PyCodeObject *
1711compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyCodeObject *co;
1714 int addNone = 1;
1715 static PyObject *module;
1716 if (!module) {
1717 module = PyUnicode_InternFromString("<module>");
1718 if (!module)
1719 return NULL;
1720 }
1721 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001722 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 return NULL;
1724 switch (mod->kind) {
1725 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001726 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 compiler_exit_scope(c);
1728 return 0;
1729 }
1730 break;
1731 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001732 if (find_ann(mod->v.Interactive.body)) {
1733 ADDOP(c, SETUP_ANNOTATIONS);
1734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 c->c_interactive = 1;
1736 VISIT_SEQ_IN_SCOPE(c, stmt,
1737 mod->v.Interactive.body);
1738 break;
1739 case Expression_kind:
1740 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1741 addNone = 0;
1742 break;
1743 case Suite_kind:
1744 PyErr_SetString(PyExc_SystemError,
1745 "suite should not be possible");
1746 return 0;
1747 default:
1748 PyErr_Format(PyExc_SystemError,
1749 "module kind %d should not be possible",
1750 mod->kind);
1751 return 0;
1752 }
1753 co = assemble(c, addNone);
1754 compiler_exit_scope(c);
1755 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001756}
1757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758/* The test for LOCAL must come before the test for FREE in order to
1759 handle classes where name is both local and free. The local var is
1760 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001761*/
1762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763static int
1764get_ref_type(struct compiler *c, PyObject *name)
1765{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001766 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001767 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001768 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001769 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001770 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (scope == 0) {
1772 char buf[350];
1773 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001774 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001776 PyUnicode_AsUTF8(name),
1777 PyUnicode_AsUTF8(c->u->u_name),
1778 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1779 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1780 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1781 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 );
1783 Py_FatalError(buf);
1784 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787}
1788
1789static int
1790compiler_lookup_arg(PyObject *dict, PyObject *name)
1791{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001792 PyObject *v;
1793 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001795 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001796 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797}
1798
1799static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001800compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001802 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001803 if (qualname == NULL)
1804 qualname = co->co_name;
1805
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001806 if (free) {
1807 for (i = 0; i < free; ++i) {
1808 /* Bypass com_addop_varname because it will generate
1809 LOAD_DEREF but LOAD_CLOSURE is needed.
1810 */
1811 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1812 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001814 /* Special case: If a class contains a method with a
1815 free variable that has the same name as a method,
1816 the name will be considered free *and* local in the
1817 class. It should be handled by the closure, as
1818 well as by the normal name loookup logic.
1819 */
1820 reftype = get_ref_type(c, name);
1821 if (reftype == CELL)
1822 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1823 else /* (reftype == FREE) */
1824 arg = compiler_lookup_arg(c->u->u_freevars, name);
1825 if (arg == -1) {
1826 fprintf(stderr,
1827 "lookup %s in %s %d %d\n"
1828 "freevars of %s: %s\n",
1829 PyUnicode_AsUTF8(PyObject_Repr(name)),
1830 PyUnicode_AsUTF8(c->u->u_name),
1831 reftype, arg,
1832 PyUnicode_AsUTF8(co->co_name),
1833 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1834 Py_FatalError("compiler_make_closure()");
1835 }
1836 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001838 flags |= 0x08;
1839 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001841 ADDOP_LOAD_CONST(c, (PyObject*)co);
1842 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001843 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845}
1846
1847static int
1848compiler_decorators(struct compiler *c, asdl_seq* decos)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (!decos)
1853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1856 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1857 }
1858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859}
1860
1861static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001862compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001864{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001865 /* Push a dict of keyword-only default values.
1866
1867 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1868 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001869 int i;
1870 PyObject *keys = NULL;
1871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1873 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1874 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1875 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001876 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001877 if (!mangled) {
1878 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001880 if (keys == NULL) {
1881 keys = PyList_New(1);
1882 if (keys == NULL) {
1883 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001884 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 }
1886 PyList_SET_ITEM(keys, 0, mangled);
1887 }
1888 else {
1889 int res = PyList_Append(keys, mangled);
1890 Py_DECREF(mangled);
1891 if (res == -1) {
1892 goto error;
1893 }
1894 }
1895 if (!compiler_visit_expr(c, default_)) {
1896 goto error;
1897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 }
1899 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001900 if (keys != NULL) {
1901 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1902 PyObject *keys_tuple = PyList_AsTuple(keys);
1903 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001904 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001906 assert(default_count > 0);
1907 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001908 }
1909 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001910 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 }
1912
1913error:
1914 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001915 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001916}
1917
1918static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001919compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1920{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001921 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001922 return 1;
1923}
1924
1925static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001926compiler_visit_argannotation(struct compiler *c, identifier id,
1927 expr_ty annotation, PyObject *names)
1928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001930 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001931 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1932 VISIT(c, annexpr, annotation)
1933 }
1934 else {
1935 VISIT(c, expr, annotation);
1936 }
Victor Stinner065efc32014-02-18 22:07:56 +01001937 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001938 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001939 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001940 if (PyList_Append(names, mangled) < 0) {
1941 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001942 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001943 }
1944 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001946 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001947}
1948
1949static int
1950compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1951 PyObject *names)
1952{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001953 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 for (i = 0; i < asdl_seq_LEN(args); i++) {
1955 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001956 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 c,
1958 arg->arg,
1959 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001960 names))
1961 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001963 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001964}
1965
1966static int
1967compiler_visit_annotations(struct compiler *c, arguments_ty args,
1968 expr_ty returns)
1969{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001970 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001971 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001972
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001973 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 */
1975 static identifier return_str;
1976 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001977 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 names = PyList_New(0);
1979 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001980 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001981
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001982 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001984 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001985 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001986 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001988 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001990 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001991 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001992 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (!return_str) {
1996 return_str = PyUnicode_InternFromString("return");
1997 if (!return_str)
1998 goto error;
1999 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002000 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 goto error;
2002 }
2003
2004 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 PyObject *keytuple = PyList_AsTuple(names);
2007 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002008 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002009 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002010 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 else {
2013 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002014 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002016
2017error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002019 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002020}
2021
2022static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002023compiler_visit_defaults(struct compiler *c, arguments_ty args)
2024{
2025 VISIT_SEQ(c, expr, args->defaults);
2026 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028}
2029
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030static Py_ssize_t
2031compiler_default_arguments(struct compiler *c, arguments_ty args)
2032{
2033 Py_ssize_t funcflags = 0;
2034 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035 if (!compiler_visit_defaults(c, args))
2036 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002037 funcflags |= 0x01;
2038 }
2039 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002041 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002042 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002043 return -1;
2044 }
2045 else if (res > 0) {
2046 funcflags |= 0x02;
2047 }
2048 }
2049 return funcflags;
2050}
2051
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052static int
Yury Selivanov75445082015-05-11 22:57:16 -04002053compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002056 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002057 arguments_ty args;
2058 expr_ty returns;
2059 identifier name;
2060 asdl_seq* decos;
2061 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002062 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002063 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002064 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002065 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066
Yury Selivanov75445082015-05-11 22:57:16 -04002067 if (is_async) {
2068 assert(s->kind == AsyncFunctionDef_kind);
2069
2070 args = s->v.AsyncFunctionDef.args;
2071 returns = s->v.AsyncFunctionDef.returns;
2072 decos = s->v.AsyncFunctionDef.decorator_list;
2073 name = s->v.AsyncFunctionDef.name;
2074 body = s->v.AsyncFunctionDef.body;
2075
2076 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2077 } else {
2078 assert(s->kind == FunctionDef_kind);
2079
2080 args = s->v.FunctionDef.args;
2081 returns = s->v.FunctionDef.returns;
2082 decos = s->v.FunctionDef.decorator_list;
2083 name = s->v.FunctionDef.name;
2084 body = s->v.FunctionDef.body;
2085
2086 scope_type = COMPILER_SCOPE_FUNCTION;
2087 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (!compiler_decorators(c, decos))
2090 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002091
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002092 firstlineno = s->lineno;
2093 if (asdl_seq_LEN(decos)) {
2094 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2095 }
2096
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002097 funcflags = compiler_default_arguments(c, args);
2098 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002100 }
2101
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002102 annotations = compiler_visit_annotations(c, args, returns);
2103 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002104 return 0;
2105 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002106 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002107 funcflags |= 0x04;
2108 }
2109
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002110 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002111 return 0;
2112 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113
INADA Naokicb41b272017-02-23 00:31:59 +09002114 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002115 if (c->c_optimize < 2) {
2116 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002117 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002118 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 compiler_exit_scope(c);
2120 return 0;
2121 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 c->u->u_argcount = asdl_seq_LEN(args->args);
2124 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002125 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002127 qualname = c->u->u_qualname;
2128 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002130 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002131 Py_XDECREF(qualname);
2132 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002134 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002136 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002137 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* decorators */
2141 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2142 ADDOP_I(c, CALL_FUNCTION, 1);
2143 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Yury Selivanov75445082015-05-11 22:57:16 -04002145 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146}
2147
2148static int
2149compiler_class(struct compiler *c, stmt_ty s)
2150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyCodeObject *co;
2152 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002153 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (!compiler_decorators(c, decos))
2157 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002158
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002159 firstlineno = s->lineno;
2160 if (asdl_seq_LEN(decos)) {
2161 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2162 }
2163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* ultimately generate code for:
2165 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2166 where:
2167 <func> is a function/closure created from the class body;
2168 it has a single argument (__locals__) where the dict
2169 (or MutableSequence) representing the locals is passed
2170 <name> is the class name
2171 <bases> is the positional arguments and *varargs argument
2172 <keywords> is the keyword arguments and **kwds argument
2173 This borrows from compiler_call.
2174 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002177 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002178 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 return 0;
2180 /* this block represents what we do in the new scope */
2181 {
2182 /* use the class name for name mangling */
2183 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002184 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* load (global) __name__ ... */
2186 str = PyUnicode_InternFromString("__name__");
2187 if (!str || !compiler_nameop(c, str, Load)) {
2188 Py_XDECREF(str);
2189 compiler_exit_scope(c);
2190 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002191 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 Py_DECREF(str);
2193 /* ... and store it as __module__ */
2194 str = PyUnicode_InternFromString("__module__");
2195 if (!str || !compiler_nameop(c, str, Store)) {
2196 Py_XDECREF(str);
2197 compiler_exit_scope(c);
2198 return 0;
2199 }
2200 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002201 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002202 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002203 str = PyUnicode_InternFromString("__qualname__");
2204 if (!str || !compiler_nameop(c, str, Store)) {
2205 Py_XDECREF(str);
2206 compiler_exit_scope(c);
2207 return 0;
2208 }
2209 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002211 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 compiler_exit_scope(c);
2213 return 0;
2214 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002215 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002216 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002217 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002218 str = PyUnicode_InternFromString("__class__");
2219 if (str == NULL) {
2220 compiler_exit_scope(c);
2221 return 0;
2222 }
2223 i = compiler_lookup_arg(c->u->u_cellvars, str);
2224 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002225 if (i < 0) {
2226 compiler_exit_scope(c);
2227 return 0;
2228 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002229 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002232 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002233 str = PyUnicode_InternFromString("__classcell__");
2234 if (!str || !compiler_nameop(c, str, Store)) {
2235 Py_XDECREF(str);
2236 compiler_exit_scope(c);
2237 return 0;
2238 }
2239 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002241 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002242 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002243 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002244 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002245 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002246 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* create the code object */
2248 co = assemble(c, 1);
2249 }
2250 /* leave the new scope */
2251 compiler_exit_scope(c);
2252 if (co == NULL)
2253 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* 2. load the 'build_class' function */
2256 ADDOP(c, LOAD_BUILD_CLASS);
2257
2258 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002259 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 Py_DECREF(co);
2261
2262 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002263 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264
2265 /* 5. generate the rest of the code for the call */
2266 if (!compiler_call_helper(c, 2,
2267 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002268 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 return 0;
2270
2271 /* 6. apply decorators */
2272 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2273 ADDOP_I(c, CALL_FUNCTION, 1);
2274 }
2275
2276 /* 7. store into <name> */
2277 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2278 return 0;
2279 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280}
2281
2282static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002283cmpop(cmpop_ty op)
2284{
2285 switch (op) {
2286 case Eq:
2287 return PyCmp_EQ;
2288 case NotEq:
2289 return PyCmp_NE;
2290 case Lt:
2291 return PyCmp_LT;
2292 case LtE:
2293 return PyCmp_LE;
2294 case Gt:
2295 return PyCmp_GT;
2296 case GtE:
2297 return PyCmp_GE;
2298 case Is:
2299 return PyCmp_IS;
2300 case IsNot:
2301 return PyCmp_IS_NOT;
2302 case In:
2303 return PyCmp_IN;
2304 case NotIn:
2305 return PyCmp_NOT_IN;
2306 default:
2307 return PyCmp_BAD;
2308 }
2309}
2310
2311static int
2312compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2313{
2314 switch (e->kind) {
2315 case UnaryOp_kind:
2316 if (e->v.UnaryOp.op == Not)
2317 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2318 /* fallback to general implementation */
2319 break;
2320 case BoolOp_kind: {
2321 asdl_seq *s = e->v.BoolOp.values;
2322 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2323 assert(n >= 0);
2324 int cond2 = e->v.BoolOp.op == Or;
2325 basicblock *next2 = next;
2326 if (!cond2 != !cond) {
2327 next2 = compiler_new_block(c);
2328 if (next2 == NULL)
2329 return 0;
2330 }
2331 for (i = 0; i < n; ++i) {
2332 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2333 return 0;
2334 }
2335 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2336 return 0;
2337 if (next2 != next)
2338 compiler_use_next_block(c, next2);
2339 return 1;
2340 }
2341 case IfExp_kind: {
2342 basicblock *end, *next2;
2343 end = compiler_new_block(c);
2344 if (end == NULL)
2345 return 0;
2346 next2 = compiler_new_block(c);
2347 if (next2 == NULL)
2348 return 0;
2349 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2350 return 0;
2351 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2352 return 0;
2353 ADDOP_JREL(c, JUMP_FORWARD, end);
2354 compiler_use_next_block(c, next2);
2355 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2356 return 0;
2357 compiler_use_next_block(c, end);
2358 return 1;
2359 }
2360 case Compare_kind: {
2361 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2362 if (n > 0) {
2363 basicblock *cleanup = compiler_new_block(c);
2364 if (cleanup == NULL)
2365 return 0;
2366 VISIT(c, expr, e->v.Compare.left);
2367 for (i = 0; i < n; i++) {
2368 VISIT(c, expr,
2369 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2370 ADDOP(c, DUP_TOP);
2371 ADDOP(c, ROT_THREE);
2372 ADDOP_I(c, COMPARE_OP,
2373 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2374 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2375 NEXT_BLOCK(c);
2376 }
2377 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2378 ADDOP_I(c, COMPARE_OP,
2379 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2380 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2381 basicblock *end = compiler_new_block(c);
2382 if (end == NULL)
2383 return 0;
2384 ADDOP_JREL(c, JUMP_FORWARD, end);
2385 compiler_use_next_block(c, cleanup);
2386 ADDOP(c, POP_TOP);
2387 if (!cond) {
2388 ADDOP_JREL(c, JUMP_FORWARD, next);
2389 }
2390 compiler_use_next_block(c, end);
2391 return 1;
2392 }
2393 /* fallback to general implementation */
2394 break;
2395 }
2396 default:
2397 /* fallback to general implementation */
2398 break;
2399 }
2400
2401 /* general implementation */
2402 VISIT(c, expr, e);
2403 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2404 return 1;
2405}
2406
2407static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002408compiler_ifexp(struct compiler *c, expr_ty e)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 basicblock *end, *next;
2411
2412 assert(e->kind == IfExp_kind);
2413 end = compiler_new_block(c);
2414 if (end == NULL)
2415 return 0;
2416 next = compiler_new_block(c);
2417 if (next == NULL)
2418 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002419 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2420 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 VISIT(c, expr, e->v.IfExp.body);
2422 ADDOP_JREL(c, JUMP_FORWARD, end);
2423 compiler_use_next_block(c, next);
2424 VISIT(c, expr, e->v.IfExp.orelse);
2425 compiler_use_next_block(c, end);
2426 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002427}
2428
2429static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002430compiler_lambda(struct compiler *c, expr_ty e)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002433 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002435 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 arguments_ty args = e->v.Lambda.args;
2437 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 if (!name) {
2440 name = PyUnicode_InternFromString("<lambda>");
2441 if (!name)
2442 return 0;
2443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002445 funcflags = compiler_default_arguments(c, args);
2446 if (funcflags == -1) {
2447 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002449
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002450 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002451 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* Make None the first constant, so the lambda can't have a
2455 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002456 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 c->u->u_argcount = asdl_seq_LEN(args->args);
2460 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2461 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2462 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002463 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 }
2465 else {
2466 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002467 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002469 qualname = c->u->u_qualname;
2470 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002472 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002475 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002476 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 Py_DECREF(co);
2478
2479 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480}
2481
2482static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483compiler_if(struct compiler *c, stmt_ty s)
2484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 basicblock *end, *next;
2486 int constant;
2487 assert(s->kind == If_kind);
2488 end = compiler_new_block(c);
2489 if (end == NULL)
2490 return 0;
2491
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002492 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* constant = 0: "if 0"
2494 * constant = 1: "if 1", "if 2", ...
2495 * constant = -1: rest */
2496 if (constant == 0) {
2497 if (s->v.If.orelse)
2498 VISIT_SEQ(c, stmt, s->v.If.orelse);
2499 } else if (constant == 1) {
2500 VISIT_SEQ(c, stmt, s->v.If.body);
2501 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002502 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 next = compiler_new_block(c);
2504 if (next == NULL)
2505 return 0;
2506 }
2507 else
2508 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002509 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2510 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002512 if (asdl_seq_LEN(s->v.If.orelse)) {
2513 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 compiler_use_next_block(c, next);
2515 VISIT_SEQ(c, stmt, s->v.If.orelse);
2516 }
2517 }
2518 compiler_use_next_block(c, end);
2519 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520}
2521
2522static int
2523compiler_for(struct compiler *c, stmt_ty s)
2524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 start = compiler_new_block(c);
2528 cleanup = compiler_new_block(c);
2529 end = compiler_new_block(c);
2530 if (start == NULL || end == NULL || cleanup == NULL)
2531 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002532
2533 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 VISIT(c, expr, s->v.For.iter);
2537 ADDOP(c, GET_ITER);
2538 compiler_use_next_block(c, start);
2539 ADDOP_JREL(c, FOR_ITER, cleanup);
2540 VISIT(c, expr, s->v.For.target);
2541 VISIT_SEQ(c, stmt, s->v.For.body);
2542 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2543 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002544
2545 compiler_pop_fblock(c, FOR_LOOP, start);
2546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 VISIT_SEQ(c, stmt, s->v.For.orelse);
2548 compiler_use_next_block(c, end);
2549 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550}
2551
Yury Selivanov75445082015-05-11 22:57:16 -04002552
2553static int
2554compiler_async_for(struct compiler *c, stmt_ty s)
2555{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002556 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002557 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2558 return compiler_error(c, "'async for' outside async function");
2559 }
2560
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002561 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002562 except = compiler_new_block(c);
2563 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002564
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002565 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002566 return 0;
2567
2568 VISIT(c, expr, s->v.AsyncFor.iter);
2569 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002570
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002571 compiler_use_next_block(c, start);
2572 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2573 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002574
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002575 /* SETUP_FINALLY to guard the __anext__ call */
2576 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002577 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002578 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002579 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002580 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002581
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002582 /* Success block for __anext__ */
2583 VISIT(c, expr, s->v.AsyncFor.target);
2584 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2585 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2586
2587 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002588
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002589 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002590 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002591 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002592
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002593 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002594 VISIT_SEQ(c, stmt, s->v.For.orelse);
2595
2596 compiler_use_next_block(c, end);
2597
2598 return 1;
2599}
2600
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601static int
2602compiler_while(struct compiler *c, stmt_ty s)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002605 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (constant == 0) {
2608 if (s->v.While.orelse)
2609 VISIT_SEQ(c, stmt, s->v.While.orelse);
2610 return 1;
2611 }
2612 loop = compiler_new_block(c);
2613 end = compiler_new_block(c);
2614 if (constant == -1) {
2615 anchor = compiler_new_block(c);
2616 if (anchor == NULL)
2617 return 0;
2618 }
2619 if (loop == NULL || end == NULL)
2620 return 0;
2621 if (s->v.While.orelse) {
2622 orelse = compiler_new_block(c);
2623 if (orelse == NULL)
2624 return 0;
2625 }
2626 else
2627 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002630 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return 0;
2632 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002633 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2634 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 }
2636 VISIT_SEQ(c, stmt, s->v.While.body);
2637 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 /* XXX should the two POP instructions be in a separate block
2640 if there is no else clause ?
2641 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002643 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002645 compiler_pop_fblock(c, WHILE_LOOP, loop);
2646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 if (orelse != NULL) /* what if orelse is just pass? */
2648 VISIT_SEQ(c, stmt, s->v.While.orelse);
2649 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652}
2653
2654static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002655compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002657 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002658 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002659 if (c->u->u_ste->ste_type != FunctionBlock)
2660 return compiler_error(c, "'return' outside function");
2661 if (s->v.Return.value != NULL &&
2662 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2663 {
2664 return compiler_error(
2665 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002667 if (preserve_tos) {
2668 VISIT(c, expr, s->v.Return.value);
2669 }
2670 for (int depth = c->u->u_nfblocks; depth--;) {
2671 struct fblockinfo *info = &c->u->u_fblock[depth];
2672
2673 if (!compiler_unwind_fblock(c, info, preserve_tos))
2674 return 0;
2675 }
2676 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002677 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002678 }
2679 else if (!preserve_tos) {
2680 VISIT(c, expr, s->v.Return.value);
2681 }
2682 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685}
2686
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002687static int
2688compiler_break(struct compiler *c)
2689{
2690 for (int depth = c->u->u_nfblocks; depth--;) {
2691 struct fblockinfo *info = &c->u->u_fblock[depth];
2692
2693 if (!compiler_unwind_fblock(c, info, 0))
2694 return 0;
2695 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2696 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2697 return 1;
2698 }
2699 }
2700 return compiler_error(c, "'break' outside loop");
2701}
2702
2703static int
2704compiler_continue(struct compiler *c)
2705{
2706 for (int depth = c->u->u_nfblocks; depth--;) {
2707 struct fblockinfo *info = &c->u->u_fblock[depth];
2708
2709 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2710 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2711 return 1;
2712 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002713 if (!compiler_unwind_fblock(c, info, 0))
2714 return 0;
2715 }
2716 return compiler_error(c, "'continue' not properly in loop");
2717}
2718
2719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721
2722 SETUP_FINALLY L
2723 <code for body>
2724 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002725 BEGIN_FINALLY
2726 L:
2727 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 END_FINALLY
2729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730 The special instructions use the block stack. Each block
2731 stack entry contains the instruction that created it (here
2732 SETUP_FINALLY), the level of the value stack at the time the
2733 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 Pushes the current value stack level and the label
2737 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002739 Pops en entry from the block stack.
2740 BEGIN_FINALLY
2741 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002743 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2744 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002747 when a SETUP_FINALLY entry is found, the raised and the caught
2748 exceptions are pushed onto the value stack (and the exception
2749 condition is cleared), and the interpreter jumps to the label
2750 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751*/
2752
2753static int
2754compiler_try_finally(struct compiler *c, stmt_ty s)
2755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 body = compiler_new_block(c);
2759 end = compiler_new_block(c);
2760 if (body == NULL || end == NULL)
2761 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002763 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 ADDOP_JREL(c, SETUP_FINALLY, end);
2765 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002766 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002768 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2769 if (!compiler_try_except(c, s))
2770 return 0;
2771 }
2772 else {
2773 VISIT_SEQ(c, stmt, s->v.Try.body);
2774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002776 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002779 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002781 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002783 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 ADDOP(c, END_FINALLY);
2785 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787}
2788
2789/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002790 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 (The contents of the value stack is shown in [], with the top
2792 at the right; 'tb' is trace-back info, 'val' the exception's
2793 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794
2795 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002796 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 [] <code for S>
2798 [] POP_BLOCK
2799 [] JUMP_FORWARD L0
2800
2801 [tb, val, exc] L1: DUP )
2802 [tb, val, exc, exc] <evaluate E1> )
2803 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2804 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2805 [tb, val, exc] POP
2806 [tb, val] <assign to V1> (or POP if no V1)
2807 [tb] POP
2808 [] <code for S1>
2809 JUMP_FORWARD L0
2810
2811 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812 .............................etc.......................
2813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2815
2816 [] L0: <next statement>
2817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818 Of course, parts are not generated if Vi or Ei is not present.
2819*/
2820static int
2821compiler_try_except(struct compiler *c, stmt_ty s)
2822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002824 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 body = compiler_new_block(c);
2827 except = compiler_new_block(c);
2828 orelse = compiler_new_block(c);
2829 end = compiler_new_block(c);
2830 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2831 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002832 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002834 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002836 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 ADDOP(c, POP_BLOCK);
2838 compiler_pop_fblock(c, EXCEPT, body);
2839 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002840 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 compiler_use_next_block(c, except);
2842 for (i = 0; i < n; i++) {
2843 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002844 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 if (!handler->v.ExceptHandler.type && i < n-1)
2846 return compiler_error(c, "default 'except:' must be last");
2847 c->u->u_lineno_set = 0;
2848 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002849 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 except = compiler_new_block(c);
2851 if (except == NULL)
2852 return 0;
2853 if (handler->v.ExceptHandler.type) {
2854 ADDOP(c, DUP_TOP);
2855 VISIT(c, expr, handler->v.ExceptHandler.type);
2856 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2857 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2858 }
2859 ADDOP(c, POP_TOP);
2860 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002861 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002862
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002863 cleanup_end = compiler_new_block(c);
2864 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002865 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002866 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002867 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002868
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002869 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2870 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002872 /*
2873 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002874 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002875 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002876 try:
2877 # body
2878 finally:
2879 name = None
2880 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002881 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002883 /* second try: */
2884 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2885 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002886 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002887 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002889 /* second # body */
2890 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2891 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 ADDOP(c, BEGIN_FINALLY);
2893 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002895 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002896 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002898 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002900 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002901 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002902 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002903 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002905 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002906 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002907 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 }
2909 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002910 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002912 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002913 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002914 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915
Guido van Rossumb940e112007-01-10 16:19:56 +00002916 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002917 ADDOP(c, POP_TOP);
2918 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002919 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002920 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002922 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002923 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 }
2925 ADDOP_JREL(c, JUMP_FORWARD, end);
2926 compiler_use_next_block(c, except);
2927 }
2928 ADDOP(c, END_FINALLY);
2929 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002930 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 compiler_use_next_block(c, end);
2932 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933}
2934
2935static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002936compiler_try(struct compiler *c, stmt_ty s) {
2937 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2938 return compiler_try_finally(c, s);
2939 else
2940 return compiler_try_except(c, s);
2941}
2942
2943
2944static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945compiler_import_as(struct compiler *c, identifier name, identifier asname)
2946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* The IMPORT_NAME opcode was already generated. This function
2948 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002951 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002953 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2954 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002956 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002959 while (1) {
2960 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002962 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002963 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002964 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002965 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002967 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002968 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002969 if (dot == -1) {
2970 break;
2971 }
2972 ADDOP(c, ROT_TWO);
2973 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002975 if (!compiler_nameop(c, asname, Store)) {
2976 return 0;
2977 }
2978 ADDOP(c, POP_TOP);
2979 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 }
2981 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
2985compiler_import(struct compiler *c, stmt_ty s)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 /* The Import node stores a module name like a.b.c as a single
2988 string. This is convenient for all cases except
2989 import a.b.c as d
2990 where we need to parse that string to extract the individual
2991 module names.
2992 XXX Perhaps change the representation to make this case simpler?
2993 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002994 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 for (i = 0; i < n; i++) {
2997 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2998 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003000 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3001 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 if (alias->asname) {
3005 r = compiler_import_as(c, alias->name, alias->asname);
3006 if (!r)
3007 return r;
3008 }
3009 else {
3010 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003011 Py_ssize_t dot = PyUnicode_FindChar(
3012 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003013 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003015 if (tmp == NULL)
3016 return 0;
3017 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 Py_DECREF(tmp);
3021 }
3022 if (!r)
3023 return r;
3024 }
3025 }
3026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027}
3028
3029static int
3030compiler_from_import(struct compiler *c, stmt_ty s)
3031{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003032 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003033 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 if (!empty_string) {
3037 empty_string = PyUnicode_FromString("");
3038 if (!empty_string)
3039 return 0;
3040 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003042 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003043
3044 names = PyTuple_New(n);
3045 if (!names)
3046 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 /* build up the names */
3049 for (i = 0; i < n; i++) {
3050 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3051 Py_INCREF(alias->name);
3052 PyTuple_SET_ITEM(names, i, alias->name);
3053 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003056 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 Py_DECREF(names);
3058 return compiler_error(c, "from __future__ imports must occur "
3059 "at the beginning of the file");
3060 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003061 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 if (s->v.ImportFrom.module) {
3064 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3065 }
3066 else {
3067 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3068 }
3069 for (i = 0; i < n; i++) {
3070 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3071 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 assert(n == 1);
3075 ADDOP(c, IMPORT_STAR);
3076 return 1;
3077 }
3078
3079 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3080 store_name = alias->name;
3081 if (alias->asname)
3082 store_name = alias->asname;
3083
3084 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 return 0;
3086 }
3087 }
3088 /* remove imported module */
3089 ADDOP(c, POP_TOP);
3090 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091}
3092
3093static int
3094compiler_assert(struct compiler *c, stmt_ty s)
3095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 static PyObject *assertion_error = NULL;
3097 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098
Georg Brandl8334fd92010-12-04 10:26:46 +00003099 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 return 1;
3101 if (assertion_error == NULL) {
3102 assertion_error = PyUnicode_InternFromString("AssertionError");
3103 if (assertion_error == NULL)
3104 return 0;
3105 }
3106 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003107 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3108 {
3109 if (!compiler_warn(c, "assertion is always true, "
3110 "perhaps remove parentheses?"))
3111 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003112 return 0;
3113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 end = compiler_new_block(c);
3116 if (end == NULL)
3117 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003118 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3119 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3121 if (s->v.Assert.msg) {
3122 VISIT(c, expr, s->v.Assert.msg);
3123 ADDOP_I(c, CALL_FUNCTION, 1);
3124 }
3125 ADDOP_I(c, RAISE_VARARGS, 1);
3126 compiler_use_next_block(c, end);
3127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128}
3129
3130static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003131compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3132{
3133 if (c->c_interactive && c->c_nestlevel <= 1) {
3134 VISIT(c, expr, value);
3135 ADDOP(c, PRINT_EXPR);
3136 return 1;
3137 }
3138
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003139 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003140 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003141 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003142 }
3143
3144 VISIT(c, expr, value);
3145 ADDOP(c, POP_TOP);
3146 return 1;
3147}
3148
3149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150compiler_visit_stmt(struct compiler *c, stmt_ty s)
3151{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003152 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* Always assign a lineno to the next instruction for a stmt. */
3155 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003156 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 switch (s->kind) {
3160 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003161 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 case ClassDef_kind:
3163 return compiler_class(c, s);
3164 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003165 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 case Delete_kind:
3167 VISIT_SEQ(c, expr, s->v.Delete.targets)
3168 break;
3169 case Assign_kind:
3170 n = asdl_seq_LEN(s->v.Assign.targets);
3171 VISIT(c, expr, s->v.Assign.value);
3172 for (i = 0; i < n; i++) {
3173 if (i < n - 1)
3174 ADDOP(c, DUP_TOP);
3175 VISIT(c, expr,
3176 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3177 }
3178 break;
3179 case AugAssign_kind:
3180 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003181 case AnnAssign_kind:
3182 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 case For_kind:
3184 return compiler_for(c, s);
3185 case While_kind:
3186 return compiler_while(c, s);
3187 case If_kind:
3188 return compiler_if(c, s);
3189 case Raise_kind:
3190 n = 0;
3191 if (s->v.Raise.exc) {
3192 VISIT(c, expr, s->v.Raise.exc);
3193 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003194 if (s->v.Raise.cause) {
3195 VISIT(c, expr, s->v.Raise.cause);
3196 n++;
3197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003199 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003201 case Try_kind:
3202 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 case Assert_kind:
3204 return compiler_assert(c, s);
3205 case Import_kind:
3206 return compiler_import(c, s);
3207 case ImportFrom_kind:
3208 return compiler_from_import(c, s);
3209 case Global_kind:
3210 case Nonlocal_kind:
3211 break;
3212 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003213 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 case Pass_kind:
3215 break;
3216 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003217 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 case Continue_kind:
3219 return compiler_continue(c);
3220 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003221 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003222 case AsyncFunctionDef_kind:
3223 return compiler_function(c, s, 1);
3224 case AsyncWith_kind:
3225 return compiler_async_with(c, s, 0);
3226 case AsyncFor_kind:
3227 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 }
Yury Selivanov75445082015-05-11 22:57:16 -04003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231}
3232
3233static int
3234unaryop(unaryop_ty op)
3235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 switch (op) {
3237 case Invert:
3238 return UNARY_INVERT;
3239 case Not:
3240 return UNARY_NOT;
3241 case UAdd:
3242 return UNARY_POSITIVE;
3243 case USub:
3244 return UNARY_NEGATIVE;
3245 default:
3246 PyErr_Format(PyExc_SystemError,
3247 "unary op %d should not be possible", op);
3248 return 0;
3249 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250}
3251
3252static int
3253binop(struct compiler *c, operator_ty op)
3254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 switch (op) {
3256 case Add:
3257 return BINARY_ADD;
3258 case Sub:
3259 return BINARY_SUBTRACT;
3260 case Mult:
3261 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003262 case MatMult:
3263 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 case Div:
3265 return BINARY_TRUE_DIVIDE;
3266 case Mod:
3267 return BINARY_MODULO;
3268 case Pow:
3269 return BINARY_POWER;
3270 case LShift:
3271 return BINARY_LSHIFT;
3272 case RShift:
3273 return BINARY_RSHIFT;
3274 case BitOr:
3275 return BINARY_OR;
3276 case BitXor:
3277 return BINARY_XOR;
3278 case BitAnd:
3279 return BINARY_AND;
3280 case FloorDiv:
3281 return BINARY_FLOOR_DIVIDE;
3282 default:
3283 PyErr_Format(PyExc_SystemError,
3284 "binary op %d should not be possible", op);
3285 return 0;
3286 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287}
3288
3289static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290inplace_binop(struct compiler *c, operator_ty op)
3291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 switch (op) {
3293 case Add:
3294 return INPLACE_ADD;
3295 case Sub:
3296 return INPLACE_SUBTRACT;
3297 case Mult:
3298 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003299 case MatMult:
3300 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 case Div:
3302 return INPLACE_TRUE_DIVIDE;
3303 case Mod:
3304 return INPLACE_MODULO;
3305 case Pow:
3306 return INPLACE_POWER;
3307 case LShift:
3308 return INPLACE_LSHIFT;
3309 case RShift:
3310 return INPLACE_RSHIFT;
3311 case BitOr:
3312 return INPLACE_OR;
3313 case BitXor:
3314 return INPLACE_XOR;
3315 case BitAnd:
3316 return INPLACE_AND;
3317 case FloorDiv:
3318 return INPLACE_FLOOR_DIVIDE;
3319 default:
3320 PyErr_Format(PyExc_SystemError,
3321 "inplace binary op %d should not be possible", op);
3322 return 0;
3323 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324}
3325
3326static int
3327compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3328{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003329 int op, scope;
3330 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 PyObject *dict = c->u->u_names;
3334 PyObject *mangled;
3335 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003337 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3338 !_PyUnicode_EqualToASCIIString(name, "True") &&
3339 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003340
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003341 mangled = _Py_Mangle(c->u->u_private, name);
3342 if (!mangled)
3343 return 0;
3344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 op = 0;
3346 optype = OP_NAME;
3347 scope = PyST_GetScope(c->u->u_ste, mangled);
3348 switch (scope) {
3349 case FREE:
3350 dict = c->u->u_freevars;
3351 optype = OP_DEREF;
3352 break;
3353 case CELL:
3354 dict = c->u->u_cellvars;
3355 optype = OP_DEREF;
3356 break;
3357 case LOCAL:
3358 if (c->u->u_ste->ste_type == FunctionBlock)
3359 optype = OP_FAST;
3360 break;
3361 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003362 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 optype = OP_GLOBAL;
3364 break;
3365 case GLOBAL_EXPLICIT:
3366 optype = OP_GLOBAL;
3367 break;
3368 default:
3369 /* scope can be 0 */
3370 break;
3371 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003374 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 switch (optype) {
3377 case OP_DEREF:
3378 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003379 case Load:
3380 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3381 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 case Store: op = STORE_DEREF; break;
3383 case AugLoad:
3384 case AugStore:
3385 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003386 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 case Param:
3388 default:
3389 PyErr_SetString(PyExc_SystemError,
3390 "param invalid for deref variable");
3391 return 0;
3392 }
3393 break;
3394 case OP_FAST:
3395 switch (ctx) {
3396 case Load: op = LOAD_FAST; break;
3397 case Store: op = STORE_FAST; break;
3398 case Del: op = DELETE_FAST; break;
3399 case AugLoad:
3400 case AugStore:
3401 break;
3402 case Param:
3403 default:
3404 PyErr_SetString(PyExc_SystemError,
3405 "param invalid for local variable");
3406 return 0;
3407 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003408 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 return 1;
3410 case OP_GLOBAL:
3411 switch (ctx) {
3412 case Load: op = LOAD_GLOBAL; break;
3413 case Store: op = STORE_GLOBAL; break;
3414 case Del: op = DELETE_GLOBAL; break;
3415 case AugLoad:
3416 case AugStore:
3417 break;
3418 case Param:
3419 default:
3420 PyErr_SetString(PyExc_SystemError,
3421 "param invalid for global variable");
3422 return 0;
3423 }
3424 break;
3425 case OP_NAME:
3426 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003427 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 case Store: op = STORE_NAME; break;
3429 case Del: op = DELETE_NAME; break;
3430 case AugLoad:
3431 case AugStore:
3432 break;
3433 case Param:
3434 default:
3435 PyErr_SetString(PyExc_SystemError,
3436 "param invalid for name variable");
3437 return 0;
3438 }
3439 break;
3440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 assert(op);
3443 arg = compiler_add_o(c, dict, mangled);
3444 Py_DECREF(mangled);
3445 if (arg < 0)
3446 return 0;
3447 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448}
3449
3450static int
3451compiler_boolop(struct compiler *c, expr_ty e)
3452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003454 int jumpi;
3455 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 assert(e->kind == BoolOp_kind);
3459 if (e->v.BoolOp.op == And)
3460 jumpi = JUMP_IF_FALSE_OR_POP;
3461 else
3462 jumpi = JUMP_IF_TRUE_OR_POP;
3463 end = compiler_new_block(c);
3464 if (end == NULL)
3465 return 0;
3466 s = e->v.BoolOp.values;
3467 n = asdl_seq_LEN(s) - 1;
3468 assert(n >= 0);
3469 for (i = 0; i < n; ++i) {
3470 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3471 ADDOP_JABS(c, jumpi, end);
3472 }
3473 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3474 compiler_use_next_block(c, end);
3475 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476}
3477
3478static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003479starunpack_helper(struct compiler *c, asdl_seq *elts,
3480 int single_op, int inner_op, int outer_op)
3481{
3482 Py_ssize_t n = asdl_seq_LEN(elts);
3483 Py_ssize_t i, nsubitems = 0, nseen = 0;
3484 for (i = 0; i < n; i++) {
3485 expr_ty elt = asdl_seq_GET(elts, i);
3486 if (elt->kind == Starred_kind) {
3487 if (nseen) {
3488 ADDOP_I(c, inner_op, nseen);
3489 nseen = 0;
3490 nsubitems++;
3491 }
3492 VISIT(c, expr, elt->v.Starred.value);
3493 nsubitems++;
3494 }
3495 else {
3496 VISIT(c, expr, elt);
3497 nseen++;
3498 }
3499 }
3500 if (nsubitems) {
3501 if (nseen) {
3502 ADDOP_I(c, inner_op, nseen);
3503 nsubitems++;
3504 }
3505 ADDOP_I(c, outer_op, nsubitems);
3506 }
3507 else
3508 ADDOP_I(c, single_op, nseen);
3509 return 1;
3510}
3511
3512static int
3513assignment_helper(struct compiler *c, asdl_seq *elts)
3514{
3515 Py_ssize_t n = asdl_seq_LEN(elts);
3516 Py_ssize_t i;
3517 int seen_star = 0;
3518 for (i = 0; i < n; i++) {
3519 expr_ty elt = asdl_seq_GET(elts, i);
3520 if (elt->kind == Starred_kind && !seen_star) {
3521 if ((i >= (1 << 8)) ||
3522 (n-i-1 >= (INT_MAX >> 8)))
3523 return compiler_error(c,
3524 "too many expressions in "
3525 "star-unpacking assignment");
3526 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3527 seen_star = 1;
3528 asdl_seq_SET(elts, i, elt->v.Starred.value);
3529 }
3530 else if (elt->kind == Starred_kind) {
3531 return compiler_error(c,
3532 "two starred expressions in assignment");
3533 }
3534 }
3535 if (!seen_star) {
3536 ADDOP_I(c, UNPACK_SEQUENCE, n);
3537 }
3538 VISIT_SEQ(c, expr, elts);
3539 return 1;
3540}
3541
3542static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543compiler_list(struct compiler *c, expr_ty e)
3544{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003545 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003547 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003549 else if (e->v.List.ctx == Load) {
3550 return starunpack_helper(c, elts,
3551 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003553 else
3554 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556}
3557
3558static int
3559compiler_tuple(struct compiler *c, expr_ty e)
3560{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003561 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003563 return assignment_helper(c, elts);
3564 }
3565 else if (e->v.Tuple.ctx == Load) {
3566 return starunpack_helper(c, elts,
3567 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3568 }
3569 else
3570 VISIT_SEQ(c, expr, elts);
3571 return 1;
3572}
3573
3574static int
3575compiler_set(struct compiler *c, expr_ty e)
3576{
3577 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3578 BUILD_SET, BUILD_SET_UNPACK);
3579}
3580
3581static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003582are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3583{
3584 Py_ssize_t i;
3585 for (i = begin; i < end; i++) {
3586 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003587 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003588 return 0;
3589 }
3590 return 1;
3591}
3592
3593static int
3594compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3595{
3596 Py_ssize_t i, n = end - begin;
3597 PyObject *keys, *key;
3598 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3599 for (i = begin; i < end; i++) {
3600 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3601 }
3602 keys = PyTuple_New(n);
3603 if (keys == NULL) {
3604 return 0;
3605 }
3606 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003607 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003608 Py_INCREF(key);
3609 PyTuple_SET_ITEM(keys, i - begin, key);
3610 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003611 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003612 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3613 }
3614 else {
3615 for (i = begin; i < end; i++) {
3616 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3617 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3618 }
3619 ADDOP_I(c, BUILD_MAP, n);
3620 }
3621 return 1;
3622}
3623
3624static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003625compiler_dict(struct compiler *c, expr_ty e)
3626{
Victor Stinner976bb402016-03-23 11:36:19 +01003627 Py_ssize_t i, n, elements;
3628 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003629 int is_unpacking = 0;
3630 n = asdl_seq_LEN(e->v.Dict.values);
3631 containers = 0;
3632 elements = 0;
3633 for (i = 0; i < n; i++) {
3634 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3635 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003636 if (!compiler_subdict(c, e, i - elements, i))
3637 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003638 containers++;
3639 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003641 if (is_unpacking) {
3642 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3643 containers++;
3644 }
3645 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003646 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 }
3648 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003649 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003650 if (!compiler_subdict(c, e, n - elements, n))
3651 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003652 containers++;
3653 }
3654 /* If there is more than one dict, they need to be merged into a new
3655 * dict. If there is one dict and it's an unpacking, then it needs
3656 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003657 if (containers > 1 || is_unpacking) {
3658 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 }
3660 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661}
3662
3663static int
3664compiler_compare(struct compiler *c, expr_ty e)
3665{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003666 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003669 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3670 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3671 if (n == 0) {
3672 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3673 ADDOP_I(c, COMPARE_OP,
3674 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3675 }
3676 else {
3677 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 if (cleanup == NULL)
3679 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003680 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 VISIT(c, expr,
3682 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003683 ADDOP(c, DUP_TOP);
3684 ADDOP(c, ROT_THREE);
3685 ADDOP_I(c, COMPARE_OP,
3686 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3687 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3688 NEXT_BLOCK(c);
3689 }
3690 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3691 ADDOP_I(c, COMPARE_OP,
3692 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 basicblock *end = compiler_new_block(c);
3694 if (end == NULL)
3695 return 0;
3696 ADDOP_JREL(c, JUMP_FORWARD, end);
3697 compiler_use_next_block(c, cleanup);
3698 ADDOP(c, ROT_TWO);
3699 ADDOP(c, POP_TOP);
3700 compiler_use_next_block(c, end);
3701 }
3702 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703}
3704
3705static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003706maybe_optimize_method_call(struct compiler *c, expr_ty e)
3707{
3708 Py_ssize_t argsl, i;
3709 expr_ty meth = e->v.Call.func;
3710 asdl_seq *args = e->v.Call.args;
3711
3712 /* Check that the call node is an attribute access, and that
3713 the call doesn't have keyword parameters. */
3714 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3715 asdl_seq_LEN(e->v.Call.keywords))
3716 return -1;
3717
3718 /* Check that there are no *varargs types of arguments. */
3719 argsl = asdl_seq_LEN(args);
3720 for (i = 0; i < argsl; i++) {
3721 expr_ty elt = asdl_seq_GET(args, i);
3722 if (elt->kind == Starred_kind) {
3723 return -1;
3724 }
3725 }
3726
3727 /* Alright, we can optimize the code. */
3728 VISIT(c, expr, meth->v.Attribute.value);
3729 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3730 VISIT_SEQ(c, expr, e->v.Call.args);
3731 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3732 return 1;
3733}
3734
3735static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736compiler_call(struct compiler *c, expr_ty e)
3737{
Yury Selivanovf2392132016-12-13 19:03:51 -05003738 if (maybe_optimize_method_call(c, e) > 0)
3739 return 1;
3740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 VISIT(c, expr, e->v.Call.func);
3742 return compiler_call_helper(c, 0,
3743 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003744 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003745}
3746
Eric V. Smith235a6f02015-09-19 14:51:32 -04003747static int
3748compiler_joined_str(struct compiler *c, expr_ty e)
3749{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003750 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003751 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3752 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003753 return 1;
3754}
3755
Eric V. Smitha78c7952015-11-03 12:45:05 -05003756/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003757static int
3758compiler_formatted_value(struct compiler *c, expr_ty e)
3759{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003760 /* Our oparg encodes 2 pieces of information: the conversion
3761 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003762
Eric V. Smitha78c7952015-11-03 12:45:05 -05003763 Convert the conversion char to 2 bits:
3764 None: 000 0x0 FVC_NONE
3765 !s : 001 0x1 FVC_STR
3766 !r : 010 0x2 FVC_REPR
3767 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003768
Eric V. Smitha78c7952015-11-03 12:45:05 -05003769 next bit is whether or not we have a format spec:
3770 yes : 100 0x4
3771 no : 000 0x0
3772 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003773
Eric V. Smitha78c7952015-11-03 12:45:05 -05003774 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003775
Eric V. Smitha78c7952015-11-03 12:45:05 -05003776 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003777 VISIT(c, expr, e->v.FormattedValue.value);
3778
Eric V. Smitha78c7952015-11-03 12:45:05 -05003779 switch (e->v.FormattedValue.conversion) {
3780 case 's': oparg = FVC_STR; break;
3781 case 'r': oparg = FVC_REPR; break;
3782 case 'a': oparg = FVC_ASCII; break;
3783 case -1: oparg = FVC_NONE; break;
3784 default:
3785 PyErr_SetString(PyExc_SystemError,
3786 "Unrecognized conversion character");
3787 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003788 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003789 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003790 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003791 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003792 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003793 }
3794
Eric V. Smitha78c7952015-11-03 12:45:05 -05003795 /* And push our opcode and oparg */
3796 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003797 return 1;
3798}
3799
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003800static int
3801compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3802{
3803 Py_ssize_t i, n = end - begin;
3804 keyword_ty kw;
3805 PyObject *keys, *key;
3806 assert(n > 0);
3807 if (n > 1) {
3808 for (i = begin; i < end; i++) {
3809 kw = asdl_seq_GET(keywords, i);
3810 VISIT(c, expr, kw->value);
3811 }
3812 keys = PyTuple_New(n);
3813 if (keys == NULL) {
3814 return 0;
3815 }
3816 for (i = begin; i < end; i++) {
3817 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3818 Py_INCREF(key);
3819 PyTuple_SET_ITEM(keys, i - begin, key);
3820 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003821 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003822 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3823 }
3824 else {
3825 /* a for loop only executes once */
3826 for (i = begin; i < end; i++) {
3827 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003828 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003829 VISIT(c, expr, kw->value);
3830 }
3831 ADDOP_I(c, BUILD_MAP, n);
3832 }
3833 return 1;
3834}
3835
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003836/* shared code between compiler_call and compiler_class */
3837static int
3838compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003839 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003840 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003841 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003842{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003843 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003844 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003845
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003846 /* the number of tuples and dictionaries on the stack */
3847 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3848
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003849 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003850 nkwelts = asdl_seq_LEN(keywords);
3851
3852 for (i = 0; i < nkwelts; i++) {
3853 keyword_ty kw = asdl_seq_GET(keywords, i);
3854 if (kw->arg == NULL) {
3855 mustdictunpack = 1;
3856 break;
3857 }
3858 }
3859
3860 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 for (i = 0; i < nelts; i++) {
3862 expr_ty elt = asdl_seq_GET(args, i);
3863 if (elt->kind == Starred_kind) {
3864 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003865 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003866 if (nseen) {
3867 ADDOP_I(c, BUILD_TUPLE, nseen);
3868 nseen = 0;
3869 nsubargs++;
3870 }
3871 VISIT(c, expr, elt->v.Starred.value);
3872 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873 }
3874 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003875 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003876 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879
3880 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003881 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003882 if (nseen) {
3883 /* Pack up any trailing positional arguments. */
3884 ADDOP_I(c, BUILD_TUPLE, nseen);
3885 nsubargs++;
3886 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003887 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003888 /* If we ended up with more than one stararg, we need
3889 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003890 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003891 }
3892 else if (nsubargs == 0) {
3893 ADDOP_I(c, BUILD_TUPLE, 0);
3894 }
3895 nseen = 0; /* the number of keyword arguments on the stack following */
3896 for (i = 0; i < nkwelts; i++) {
3897 keyword_ty kw = asdl_seq_GET(keywords, i);
3898 if (kw->arg == NULL) {
3899 /* A keyword argument unpacking. */
3900 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003901 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3902 return 0;
3903 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003904 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003905 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003906 VISIT(c, expr, kw->value);
3907 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003908 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003909 else {
3910 nseen++;
3911 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003912 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003913 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003914 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003915 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003916 return 0;
3917 nsubkwargs++;
3918 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003919 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003920 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003921 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003922 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003923 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3924 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003926 else if (nkwelts) {
3927 PyObject *names;
3928 VISIT_SEQ(c, keyword, keywords);
3929 names = PyTuple_New(nkwelts);
3930 if (names == NULL) {
3931 return 0;
3932 }
3933 for (i = 0; i < nkwelts; i++) {
3934 keyword_ty kw = asdl_seq_GET(keywords, i);
3935 Py_INCREF(kw->arg);
3936 PyTuple_SET_ITEM(names, i, kw->arg);
3937 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003938 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003939 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3940 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003942 else {
3943 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3944 return 1;
3945 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946}
3947
Nick Coghlan650f0d02007-04-15 12:05:43 +00003948
3949/* List and set comprehensions and generator expressions work by creating a
3950 nested function to perform the actual iteration. This means that the
3951 iteration variables don't leak into the current scope.
3952 The defined function is called immediately following its definition, with the
3953 result of that call being the result of the expression.
3954 The LC/SC version returns the populated container, while the GE version is
3955 flagged in symtable.c as a generator, so it returns the generator object
3956 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003957
3958 Possible cleanups:
3959 - iterate over the generator sequence instead of using recursion
3960*/
3961
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003962
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003963static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964compiler_comprehension_generator(struct compiler *c,
3965 asdl_seq *generators, int gen_index,
3966 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968 comprehension_ty gen;
3969 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3970 if (gen->is_async) {
3971 return compiler_async_comprehension_generator(
3972 c, generators, gen_index, elt, val, type);
3973 } else {
3974 return compiler_sync_comprehension_generator(
3975 c, generators, gen_index, elt, val, type);
3976 }
3977}
3978
3979static int
3980compiler_sync_comprehension_generator(struct compiler *c,
3981 asdl_seq *generators, int gen_index,
3982 expr_ty elt, expr_ty val, int type)
3983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 /* generate code for the iterator, then each of the ifs,
3985 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 comprehension_ty gen;
3988 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003989 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 start = compiler_new_block(c);
3992 skip = compiler_new_block(c);
3993 if_cleanup = compiler_new_block(c);
3994 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3997 anchor == NULL)
3998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 if (gen_index == 0) {
4003 /* Receive outermost iter as an implicit argument */
4004 c->u->u_argcount = 1;
4005 ADDOP_I(c, LOAD_FAST, 0);
4006 }
4007 else {
4008 /* Sub-iter - calculate on the fly */
4009 VISIT(c, expr, gen->iter);
4010 ADDOP(c, GET_ITER);
4011 }
4012 compiler_use_next_block(c, start);
4013 ADDOP_JREL(c, FOR_ITER, anchor);
4014 NEXT_BLOCK(c);
4015 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* XXX this needs to be cleaned up...a lot! */
4018 n = asdl_seq_LEN(gen->ifs);
4019 for (i = 0; i < n; i++) {
4020 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004021 if (!compiler_jump_if(c, e, if_cleanup, 0))
4022 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 NEXT_BLOCK(c);
4024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (++gen_index < asdl_seq_LEN(generators))
4027 if (!compiler_comprehension_generator(c,
4028 generators, gen_index,
4029 elt, val, type))
4030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 /* only append after the last for generator */
4033 if (gen_index >= asdl_seq_LEN(generators)) {
4034 /* comprehension specific code */
4035 switch (type) {
4036 case COMP_GENEXP:
4037 VISIT(c, expr, elt);
4038 ADDOP(c, YIELD_VALUE);
4039 ADDOP(c, POP_TOP);
4040 break;
4041 case COMP_LISTCOMP:
4042 VISIT(c, expr, elt);
4043 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4044 break;
4045 case COMP_SETCOMP:
4046 VISIT(c, expr, elt);
4047 ADDOP_I(c, SET_ADD, gen_index + 1);
4048 break;
4049 case COMP_DICTCOMP:
4050 /* With 'd[k] = v', v is evaluated before k, so we do
4051 the same. */
4052 VISIT(c, expr, val);
4053 VISIT(c, expr, elt);
4054 ADDOP_I(c, MAP_ADD, gen_index + 1);
4055 break;
4056 default:
4057 return 0;
4058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 compiler_use_next_block(c, skip);
4061 }
4062 compiler_use_next_block(c, if_cleanup);
4063 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4064 compiler_use_next_block(c, anchor);
4065
4066 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067}
4068
4069static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004070compiler_async_comprehension_generator(struct compiler *c,
4071 asdl_seq *generators, int gen_index,
4072 expr_ty elt, expr_ty val, int type)
4073{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004074 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004075 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004076 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004077 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004078 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004079 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004080
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004081 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004082 return 0;
4083 }
4084
4085 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4086
4087 if (gen_index == 0) {
4088 /* Receive outermost iter as an implicit argument */
4089 c->u->u_argcount = 1;
4090 ADDOP_I(c, LOAD_FAST, 0);
4091 }
4092 else {
4093 /* Sub-iter - calculate on the fly */
4094 VISIT(c, expr, gen->iter);
4095 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004096 }
4097
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004098 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004099
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004100 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004101 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004102 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004103 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004104 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004105 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004106
4107 n = asdl_seq_LEN(gen->ifs);
4108 for (i = 0; i < n; i++) {
4109 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004110 if (!compiler_jump_if(c, e, if_cleanup, 0))
4111 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004112 NEXT_BLOCK(c);
4113 }
4114
4115 if (++gen_index < asdl_seq_LEN(generators))
4116 if (!compiler_comprehension_generator(c,
4117 generators, gen_index,
4118 elt, val, type))
4119 return 0;
4120
4121 /* only append after the last for generator */
4122 if (gen_index >= asdl_seq_LEN(generators)) {
4123 /* comprehension specific code */
4124 switch (type) {
4125 case COMP_GENEXP:
4126 VISIT(c, expr, elt);
4127 ADDOP(c, YIELD_VALUE);
4128 ADDOP(c, POP_TOP);
4129 break;
4130 case COMP_LISTCOMP:
4131 VISIT(c, expr, elt);
4132 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4133 break;
4134 case COMP_SETCOMP:
4135 VISIT(c, expr, elt);
4136 ADDOP_I(c, SET_ADD, gen_index + 1);
4137 break;
4138 case COMP_DICTCOMP:
4139 /* With 'd[k] = v', v is evaluated before k, so we do
4140 the same. */
4141 VISIT(c, expr, val);
4142 VISIT(c, expr, elt);
4143 ADDOP_I(c, MAP_ADD, gen_index + 1);
4144 break;
4145 default:
4146 return 0;
4147 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004148 }
4149 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004150 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4151
4152 compiler_use_next_block(c, except);
4153 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004154
4155 return 1;
4156}
4157
4158static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004159compiler_comprehension(struct compiler *c, expr_ty e, int type,
4160 identifier name, asdl_seq *generators, expr_ty elt,
4161 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004164 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004165 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004166 int is_async_function = c->u->u_ste->ste_coroutine;
4167 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004168
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004169 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004170
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004171 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4172 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004173 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004175 }
4176
4177 is_async_generator = c->u->u_ste->ste_coroutine;
4178
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004179 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004180 compiler_error(c, "asynchronous comprehension outside of "
4181 "an asynchronous function");
4182 goto error_in_scope;
4183 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 if (type != COMP_GENEXP) {
4186 int op;
4187 switch (type) {
4188 case COMP_LISTCOMP:
4189 op = BUILD_LIST;
4190 break;
4191 case COMP_SETCOMP:
4192 op = BUILD_SET;
4193 break;
4194 case COMP_DICTCOMP:
4195 op = BUILD_MAP;
4196 break;
4197 default:
4198 PyErr_Format(PyExc_SystemError,
4199 "unknown comprehension type %d", type);
4200 goto error_in_scope;
4201 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 ADDOP_I(c, op, 0);
4204 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 if (!compiler_comprehension_generator(c, generators, 0, elt,
4207 val, type))
4208 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (type != COMP_GENEXP) {
4211 ADDOP(c, RETURN_VALUE);
4212 }
4213
4214 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004215 qualname = c->u->u_qualname;
4216 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004218 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 goto error;
4220
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004221 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004223 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 Py_DECREF(co);
4225
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004226 VISIT(c, expr, outermost->iter);
4227
4228 if (outermost->is_async) {
4229 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004230 } else {
4231 ADDOP(c, GET_ITER);
4232 }
4233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004235
4236 if (is_async_generator && type != COMP_GENEXP) {
4237 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004238 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004239 ADDOP(c, YIELD_FROM);
4240 }
4241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004243error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004245error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004246 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 Py_XDECREF(co);
4248 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004249}
4250
4251static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252compiler_genexp(struct compiler *c, expr_ty e)
4253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 static identifier name;
4255 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004256 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 if (!name)
4258 return 0;
4259 }
4260 assert(e->kind == GeneratorExp_kind);
4261 return compiler_comprehension(c, e, COMP_GENEXP, name,
4262 e->v.GeneratorExp.generators,
4263 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264}
4265
4266static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004267compiler_listcomp(struct compiler *c, expr_ty e)
4268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 static identifier name;
4270 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004271 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 if (!name)
4273 return 0;
4274 }
4275 assert(e->kind == ListComp_kind);
4276 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4277 e->v.ListComp.generators,
4278 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004279}
4280
4281static int
4282compiler_setcomp(struct compiler *c, expr_ty e)
4283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 static identifier name;
4285 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004286 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (!name)
4288 return 0;
4289 }
4290 assert(e->kind == SetComp_kind);
4291 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4292 e->v.SetComp.generators,
4293 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004294}
4295
4296
4297static int
4298compiler_dictcomp(struct compiler *c, expr_ty e)
4299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 static identifier name;
4301 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004302 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 if (!name)
4304 return 0;
4305 }
4306 assert(e->kind == DictComp_kind);
4307 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4308 e->v.DictComp.generators,
4309 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004310}
4311
4312
4313static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004314compiler_visit_keyword(struct compiler *c, keyword_ty k)
4315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 VISIT(c, expr, k->value);
4317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004318}
4319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321 whether they are true or false.
4322
4323 Return values: 1 for true, 0 for false, -1 for non-constant.
4324 */
4325
4326static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004327expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004329 if (e->kind == Constant_kind) {
4330 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004331 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004332 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004333}
4334
Yury Selivanov75445082015-05-11 22:57:16 -04004335
4336/*
4337 Implements the async with statement.
4338
4339 The semantics outlined in that PEP are as follows:
4340
4341 async with EXPR as VAR:
4342 BLOCK
4343
4344 It is implemented roughly as:
4345
4346 context = EXPR
4347 exit = context.__aexit__ # not calling it
4348 value = await context.__aenter__()
4349 try:
4350 VAR = value # if VAR present in the syntax
4351 BLOCK
4352 finally:
4353 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004354 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004355 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004356 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004357 if not (await exit(*exc)):
4358 raise
4359 */
4360static int
4361compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4362{
4363 basicblock *block, *finally;
4364 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4365
4366 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004367 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4368 return compiler_error(c, "'async with' outside async function");
4369 }
Yury Selivanov75445082015-05-11 22:57:16 -04004370
4371 block = compiler_new_block(c);
4372 finally = compiler_new_block(c);
4373 if (!block || !finally)
4374 return 0;
4375
4376 /* Evaluate EXPR */
4377 VISIT(c, expr, item->context_expr);
4378
4379 ADDOP(c, BEFORE_ASYNC_WITH);
4380 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004381 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004382 ADDOP(c, YIELD_FROM);
4383
4384 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4385
4386 /* SETUP_ASYNC_WITH pushes a finally block. */
4387 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004388 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004389 return 0;
4390 }
4391
4392 if (item->optional_vars) {
4393 VISIT(c, expr, item->optional_vars);
4394 }
4395 else {
4396 /* Discard result from context.__aenter__() */
4397 ADDOP(c, POP_TOP);
4398 }
4399
4400 pos++;
4401 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4402 /* BLOCK code */
4403 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4404 else if (!compiler_async_with(c, s, pos))
4405 return 0;
4406
4407 /* End of try block; start the finally block */
4408 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004409 ADDOP(c, BEGIN_FINALLY);
4410 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004411
Yury Selivanov75445082015-05-11 22:57:16 -04004412 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004413 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004414 return 0;
4415
4416 /* Finally block starts; context.__exit__ is on the stack under
4417 the exception or return information. Just issue our magic
4418 opcode. */
4419 ADDOP(c, WITH_CLEANUP_START);
4420
4421 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004422 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004423 ADDOP(c, YIELD_FROM);
4424
4425 ADDOP(c, WITH_CLEANUP_FINISH);
4426
4427 /* Finally block ends. */
4428 ADDOP(c, END_FINALLY);
4429 compiler_pop_fblock(c, FINALLY_END, finally);
4430 return 1;
4431}
4432
4433
Guido van Rossumc2e20742006-02-27 22:32:47 +00004434/*
4435 Implements the with statement from PEP 343.
4436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004438
4439 with EXPR as VAR:
4440 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441
Guido van Rossumc2e20742006-02-27 22:32:47 +00004442 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443
Thomas Wouters477c8d52006-05-27 19:21:47 +00004444 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004445 exit = context.__exit__ # not calling it
4446 value = context.__enter__()
4447 try:
4448 VAR = value # if VAR present in the syntax
4449 BLOCK
4450 finally:
4451 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004452 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004453 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004454 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004455 exit(*exc)
4456 */
4457static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004458compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004459{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004460 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004461 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004462
4463 assert(s->kind == With_kind);
4464
Guido van Rossumc2e20742006-02-27 22:32:47 +00004465 block = compiler_new_block(c);
4466 finally = compiler_new_block(c);
4467 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004468 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004469
Thomas Wouters477c8d52006-05-27 19:21:47 +00004470 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004471 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004472 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004473
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004474 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004475 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004476 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004477 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004478 }
4479
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004480 if (item->optional_vars) {
4481 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004482 }
4483 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004485 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004486 }
4487
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004488 pos++;
4489 if (pos == asdl_seq_LEN(s->v.With.items))
4490 /* BLOCK code */
4491 VISIT_SEQ(c, stmt, s->v.With.body)
4492 else if (!compiler_with(c, s, pos))
4493 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004494
4495 /* End of try block; start the finally block */
4496 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004497 ADDOP(c, BEGIN_FINALLY);
4498 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004499
Guido van Rossumc2e20742006-02-27 22:32:47 +00004500 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004501 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004502 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004503
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004504 /* Finally block starts; context.__exit__ is on the stack under
4505 the exception or return information. Just issue our magic
4506 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004507 ADDOP(c, WITH_CLEANUP_START);
4508 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004509
4510 /* Finally block ends. */
4511 ADDOP(c, END_FINALLY);
4512 compiler_pop_fblock(c, FINALLY_END, finally);
4513 return 1;
4514}
4515
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004516static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004517compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 switch (e->kind) {
4520 case BoolOp_kind:
4521 return compiler_boolop(c, e);
4522 case BinOp_kind:
4523 VISIT(c, expr, e->v.BinOp.left);
4524 VISIT(c, expr, e->v.BinOp.right);
4525 ADDOP(c, binop(c, e->v.BinOp.op));
4526 break;
4527 case UnaryOp_kind:
4528 VISIT(c, expr, e->v.UnaryOp.operand);
4529 ADDOP(c, unaryop(e->v.UnaryOp.op));
4530 break;
4531 case Lambda_kind:
4532 return compiler_lambda(c, e);
4533 case IfExp_kind:
4534 return compiler_ifexp(c, e);
4535 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004536 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004538 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 case GeneratorExp_kind:
4540 return compiler_genexp(c, e);
4541 case ListComp_kind:
4542 return compiler_listcomp(c, e);
4543 case SetComp_kind:
4544 return compiler_setcomp(c, e);
4545 case DictComp_kind:
4546 return compiler_dictcomp(c, e);
4547 case Yield_kind:
4548 if (c->u->u_ste->ste_type != FunctionBlock)
4549 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004550 if (e->v.Yield.value) {
4551 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 }
4553 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004554 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004556 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004558 case YieldFrom_kind:
4559 if (c->u->u_ste->ste_type != FunctionBlock)
4560 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004561
4562 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4563 return compiler_error(c, "'yield from' inside async function");
4564
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004565 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004566 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004567 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004568 ADDOP(c, YIELD_FROM);
4569 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004570 case Await_kind:
4571 if (c->u->u_ste->ste_type != FunctionBlock)
4572 return compiler_error(c, "'await' outside function");
4573
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4575 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004576 return compiler_error(c, "'await' outside async function");
4577
4578 VISIT(c, expr, e->v.Await.value);
4579 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004580 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004581 ADDOP(c, YIELD_FROM);
4582 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 case Compare_kind:
4584 return compiler_compare(c, e);
4585 case Call_kind:
4586 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004587 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004588 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004589 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004590 case JoinedStr_kind:
4591 return compiler_joined_str(c, e);
4592 case FormattedValue_kind:
4593 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 /* The following exprs can be assignment targets. */
4595 case Attribute_kind:
4596 if (e->v.Attribute.ctx != AugStore)
4597 VISIT(c, expr, e->v.Attribute.value);
4598 switch (e->v.Attribute.ctx) {
4599 case AugLoad:
4600 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004601 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 case Load:
4603 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4604 break;
4605 case AugStore:
4606 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004607 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 case Store:
4609 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4610 break;
4611 case Del:
4612 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4613 break;
4614 case Param:
4615 default:
4616 PyErr_SetString(PyExc_SystemError,
4617 "param invalid in attribute expression");
4618 return 0;
4619 }
4620 break;
4621 case Subscript_kind:
4622 switch (e->v.Subscript.ctx) {
4623 case AugLoad:
4624 VISIT(c, expr, e->v.Subscript.value);
4625 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4626 break;
4627 case Load:
4628 VISIT(c, expr, e->v.Subscript.value);
4629 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4630 break;
4631 case AugStore:
4632 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4633 break;
4634 case Store:
4635 VISIT(c, expr, e->v.Subscript.value);
4636 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4637 break;
4638 case Del:
4639 VISIT(c, expr, e->v.Subscript.value);
4640 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4641 break;
4642 case Param:
4643 default:
4644 PyErr_SetString(PyExc_SystemError,
4645 "param invalid in subscript expression");
4646 return 0;
4647 }
4648 break;
4649 case Starred_kind:
4650 switch (e->v.Starred.ctx) {
4651 case Store:
4652 /* In all legitimate cases, the Starred node was already replaced
4653 * by compiler_list/compiler_tuple. XXX: is that okay? */
4654 return compiler_error(c,
4655 "starred assignment target must be in a list or tuple");
4656 default:
4657 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004658 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 }
4660 break;
4661 case Name_kind:
4662 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4663 /* child nodes of List and Tuple will have expr_context set */
4664 case List_kind:
4665 return compiler_list(c, e);
4666 case Tuple_kind:
4667 return compiler_tuple(c, e);
4668 }
4669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004670}
4671
4672static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004673compiler_visit_expr(struct compiler *c, expr_ty e)
4674{
4675 /* If expr e has a different line number than the last expr/stmt,
4676 set a new line number for the next instruction.
4677 */
4678 int old_lineno = c->u->u_lineno;
4679 int old_col_offset = c->u->u_col_offset;
4680 if (e->lineno != c->u->u_lineno) {
4681 c->u->u_lineno = e->lineno;
4682 c->u->u_lineno_set = 0;
4683 }
4684 /* Updating the column offset is always harmless. */
4685 c->u->u_col_offset = e->col_offset;
4686
4687 int res = compiler_visit_expr1(c, e);
4688
4689 if (old_lineno != c->u->u_lineno) {
4690 c->u->u_lineno = old_lineno;
4691 c->u->u_lineno_set = 0;
4692 }
4693 c->u->u_col_offset = old_col_offset;
4694 return res;
4695}
4696
4697static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698compiler_augassign(struct compiler *c, stmt_ty s)
4699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 expr_ty e = s->v.AugAssign.target;
4701 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 switch (e->kind) {
4706 case Attribute_kind:
4707 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4708 AugLoad, e->lineno, e->col_offset, c->c_arena);
4709 if (auge == NULL)
4710 return 0;
4711 VISIT(c, expr, auge);
4712 VISIT(c, expr, s->v.AugAssign.value);
4713 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4714 auge->v.Attribute.ctx = AugStore;
4715 VISIT(c, expr, auge);
4716 break;
4717 case Subscript_kind:
4718 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4719 AugLoad, e->lineno, e->col_offset, c->c_arena);
4720 if (auge == NULL)
4721 return 0;
4722 VISIT(c, expr, auge);
4723 VISIT(c, expr, s->v.AugAssign.value);
4724 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4725 auge->v.Subscript.ctx = AugStore;
4726 VISIT(c, expr, auge);
4727 break;
4728 case Name_kind:
4729 if (!compiler_nameop(c, e->v.Name.id, Load))
4730 return 0;
4731 VISIT(c, expr, s->v.AugAssign.value);
4732 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4733 return compiler_nameop(c, e->v.Name.id, Store);
4734 default:
4735 PyErr_Format(PyExc_SystemError,
4736 "invalid node type (%d) for augmented assignment",
4737 e->kind);
4738 return 0;
4739 }
4740 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004741}
4742
4743static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004744check_ann_expr(struct compiler *c, expr_ty e)
4745{
4746 VISIT(c, expr, e);
4747 ADDOP(c, POP_TOP);
4748 return 1;
4749}
4750
4751static int
4752check_annotation(struct compiler *c, stmt_ty s)
4753{
4754 /* Annotations are only evaluated in a module or class. */
4755 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4756 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4757 return check_ann_expr(c, s->v.AnnAssign.annotation);
4758 }
4759 return 1;
4760}
4761
4762static int
4763check_ann_slice(struct compiler *c, slice_ty sl)
4764{
4765 switch(sl->kind) {
4766 case Index_kind:
4767 return check_ann_expr(c, sl->v.Index.value);
4768 case Slice_kind:
4769 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4770 return 0;
4771 }
4772 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4773 return 0;
4774 }
4775 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4776 return 0;
4777 }
4778 break;
4779 default:
4780 PyErr_SetString(PyExc_SystemError,
4781 "unexpected slice kind");
4782 return 0;
4783 }
4784 return 1;
4785}
4786
4787static int
4788check_ann_subscr(struct compiler *c, slice_ty sl)
4789{
4790 /* We check that everything in a subscript is defined at runtime. */
4791 Py_ssize_t i, n;
4792
4793 switch (sl->kind) {
4794 case Index_kind:
4795 case Slice_kind:
4796 if (!check_ann_slice(c, sl)) {
4797 return 0;
4798 }
4799 break;
4800 case ExtSlice_kind:
4801 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4802 for (i = 0; i < n; i++) {
4803 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4804 switch (subsl->kind) {
4805 case Index_kind:
4806 case Slice_kind:
4807 if (!check_ann_slice(c, subsl)) {
4808 return 0;
4809 }
4810 break;
4811 case ExtSlice_kind:
4812 default:
4813 PyErr_SetString(PyExc_SystemError,
4814 "extended slice invalid in nested slice");
4815 return 0;
4816 }
4817 }
4818 break;
4819 default:
4820 PyErr_Format(PyExc_SystemError,
4821 "invalid subscript kind %d", sl->kind);
4822 return 0;
4823 }
4824 return 1;
4825}
4826
4827static int
4828compiler_annassign(struct compiler *c, stmt_ty s)
4829{
4830 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004831 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004832
4833 assert(s->kind == AnnAssign_kind);
4834
4835 /* We perform the actual assignment first. */
4836 if (s->v.AnnAssign.value) {
4837 VISIT(c, expr, s->v.AnnAssign.value);
4838 VISIT(c, expr, targ);
4839 }
4840 switch (targ->kind) {
4841 case Name_kind:
4842 /* If we have a simple name in a module or class, store annotation. */
4843 if (s->v.AnnAssign.simple &&
4844 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4845 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004846 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4847 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4848 }
4849 else {
4850 VISIT(c, expr, s->v.AnnAssign.annotation);
4851 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004852 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004853 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004854 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004855 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004856 }
4857 break;
4858 case Attribute_kind:
4859 if (!s->v.AnnAssign.value &&
4860 !check_ann_expr(c, targ->v.Attribute.value)) {
4861 return 0;
4862 }
4863 break;
4864 case Subscript_kind:
4865 if (!s->v.AnnAssign.value &&
4866 (!check_ann_expr(c, targ->v.Subscript.value) ||
4867 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4868 return 0;
4869 }
4870 break;
4871 default:
4872 PyErr_Format(PyExc_SystemError,
4873 "invalid node type (%d) for annotated assignment",
4874 targ->kind);
4875 return 0;
4876 }
4877 /* Annotation is evaluated last. */
4878 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4879 return 0;
4880 }
4881 return 1;
4882}
4883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884/* Raises a SyntaxError and returns 0.
4885 If something goes wrong, a different exception may be raised.
4886*/
4887
4888static int
4889compiler_error(struct compiler *c, const char *errstr)
4890{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004891 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893
Victor Stinner14e461d2013-08-26 22:28:21 +02004894 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 if (!loc) {
4896 Py_INCREF(Py_None);
4897 loc = Py_None;
4898 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004899 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004900 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 if (!u)
4902 goto exit;
4903 v = Py_BuildValue("(zO)", errstr, u);
4904 if (!v)
4905 goto exit;
4906 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004907 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 Py_DECREF(loc);
4909 Py_XDECREF(u);
4910 Py_XDECREF(v);
4911 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004912}
4913
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004914/* Emits a SyntaxWarning and returns 1 on success.
4915 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4916 and returns 0.
4917*/
4918static int
4919compiler_warn(struct compiler *c, const char *errstr)
4920{
4921 PyObject *msg = PyUnicode_FromString(errstr);
4922 if (msg == NULL) {
4923 return 0;
4924 }
4925 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4926 c->u->u_lineno, NULL, NULL) < 0)
4927 {
4928 Py_DECREF(msg);
4929 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4930 PyErr_Clear();
4931 return compiler_error(c, errstr);
4932 }
4933 return 0;
4934 }
4935 Py_DECREF(msg);
4936 return 1;
4937}
4938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004939static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940compiler_handle_subscr(struct compiler *c, const char *kind,
4941 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 /* XXX this code is duplicated */
4946 switch (ctx) {
4947 case AugLoad: /* fall through to Load */
4948 case Load: op = BINARY_SUBSCR; break;
4949 case AugStore:/* fall through to Store */
4950 case Store: op = STORE_SUBSCR; break;
4951 case Del: op = DELETE_SUBSCR; break;
4952 case Param:
4953 PyErr_Format(PyExc_SystemError,
4954 "invalid %s kind %d in subscript\n",
4955 kind, ctx);
4956 return 0;
4957 }
4958 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004959 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 }
4961 else if (ctx == AugStore) {
4962 ADDOP(c, ROT_THREE);
4963 }
4964 ADDOP(c, op);
4965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966}
4967
4968static int
4969compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 int n = 2;
4972 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 /* only handles the cases where BUILD_SLICE is emitted */
4975 if (s->v.Slice.lower) {
4976 VISIT(c, expr, s->v.Slice.lower);
4977 }
4978 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004979 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 if (s->v.Slice.upper) {
4983 VISIT(c, expr, s->v.Slice.upper);
4984 }
4985 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004986 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 }
4988
4989 if (s->v.Slice.step) {
4990 n++;
4991 VISIT(c, expr, s->v.Slice.step);
4992 }
4993 ADDOP_I(c, BUILD_SLICE, n);
4994 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004995}
4996
4997static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4999 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 switch (s->kind) {
5002 case Slice_kind:
5003 return compiler_slice(c, s, ctx);
5004 case Index_kind:
5005 VISIT(c, expr, s->v.Index.value);
5006 break;
5007 case ExtSlice_kind:
5008 default:
5009 PyErr_SetString(PyExc_SystemError,
5010 "extended slice invalid in nested slice");
5011 return 0;
5012 }
5013 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005014}
5015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005016static int
5017compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5018{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005019 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 switch (s->kind) {
5021 case Index_kind:
5022 kindname = "index";
5023 if (ctx != AugStore) {
5024 VISIT(c, expr, s->v.Index.value);
5025 }
5026 break;
5027 case Slice_kind:
5028 kindname = "slice";
5029 if (ctx != AugStore) {
5030 if (!compiler_slice(c, s, ctx))
5031 return 0;
5032 }
5033 break;
5034 case ExtSlice_kind:
5035 kindname = "extended slice";
5036 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005037 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 for (i = 0; i < n; i++) {
5039 slice_ty sub = (slice_ty)asdl_seq_GET(
5040 s->v.ExtSlice.dims, i);
5041 if (!compiler_visit_nested_slice(c, sub, ctx))
5042 return 0;
5043 }
5044 ADDOP_I(c, BUILD_TUPLE, n);
5045 }
5046 break;
5047 default:
5048 PyErr_Format(PyExc_SystemError,
5049 "invalid subscript kind %d", s->kind);
5050 return 0;
5051 }
5052 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005053}
5054
Thomas Wouters89f507f2006-12-13 04:49:30 +00005055/* End of the compiler section, beginning of the assembler section */
5056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005057/* do depth-first search of basic block graph, starting with block.
5058 post records the block indices in post-order.
5059
5060 XXX must handle implicit jumps from one block to next
5061*/
5062
Thomas Wouters89f507f2006-12-13 04:49:30 +00005063struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 PyObject *a_bytecode; /* string containing bytecode */
5065 int a_offset; /* offset into bytecode */
5066 int a_nblocks; /* number of reachable blocks */
5067 basicblock **a_postorder; /* list of blocks in dfs postorder */
5068 PyObject *a_lnotab; /* string containing lnotab */
5069 int a_lnotab_off; /* offset into lnotab */
5070 int a_lineno; /* last lineno of emitted instruction */
5071 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005072};
5073
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005074static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005075dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005076{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005077 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005078
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005079 /* Get rid of recursion for normal control flow.
5080 Since the number of blocks is limited, unused space in a_postorder
5081 (from a_nblocks to end) can be used as a stack for still not ordered
5082 blocks. */
5083 for (j = end; b && !b->b_seen; b = b->b_next) {
5084 b->b_seen = 1;
5085 assert(a->a_nblocks < j);
5086 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005088 while (j < end) {
5089 b = a->a_postorder[j++];
5090 for (i = 0; i < b->b_iused; i++) {
5091 struct instr *instr = &b->b_instr[i];
5092 if (instr->i_jrel || instr->i_jabs)
5093 dfs(c, instr->i_target, a, j);
5094 }
5095 assert(a->a_nblocks < j);
5096 a->a_postorder[a->a_nblocks++] = b;
5097 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005098}
5099
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005100Py_LOCAL_INLINE(void)
5101stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005103 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005104 if (b->b_startdepth < depth) {
5105 assert(b->b_startdepth < 0);
5106 b->b_startdepth = depth;
5107 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005108 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005109}
5110
5111/* Find the flow path that needs the largest stack. We assume that
5112 * cycles in the flow graph have no net effect on the stack depth.
5113 */
5114static int
5115stackdepth(struct compiler *c)
5116{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005117 basicblock *b, *entryblock = NULL;
5118 basicblock **stack, **sp;
5119 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 b->b_startdepth = INT_MIN;
5122 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005123 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 }
5125 if (!entryblock)
5126 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005127 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5128 if (!stack) {
5129 PyErr_NoMemory();
5130 return -1;
5131 }
5132
5133 sp = stack;
5134 stackdepth_push(&sp, entryblock, 0);
5135 while (sp != stack) {
5136 b = *--sp;
5137 int depth = b->b_startdepth;
5138 assert(depth >= 0);
5139 basicblock *next = b->b_next;
5140 for (int i = 0; i < b->b_iused; i++) {
5141 struct instr *instr = &b->b_instr[i];
5142 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5143 if (effect == PY_INVALID_STACK_EFFECT) {
5144 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5145 Py_FatalError("PyCompile_OpcodeStackEffect()");
5146 }
5147 int new_depth = depth + effect;
5148 if (new_depth > maxdepth) {
5149 maxdepth = new_depth;
5150 }
5151 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5152 if (instr->i_jrel || instr->i_jabs) {
5153 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5154 assert(effect != PY_INVALID_STACK_EFFECT);
5155 int target_depth = depth + effect;
5156 if (target_depth > maxdepth) {
5157 maxdepth = target_depth;
5158 }
5159 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005160 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005161 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005162 assert(instr->i_target->b_startdepth >= target_depth);
5163 depth = new_depth;
5164 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005165 }
5166 stackdepth_push(&sp, instr->i_target, target_depth);
5167 }
5168 depth = new_depth;
5169 if (instr->i_opcode == JUMP_ABSOLUTE ||
5170 instr->i_opcode == JUMP_FORWARD ||
5171 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005172 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005173 {
5174 /* remaining code is dead */
5175 next = NULL;
5176 break;
5177 }
5178 }
5179 if (next != NULL) {
5180 stackdepth_push(&sp, next, depth);
5181 }
5182 }
5183 PyObject_Free(stack);
5184 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005185}
5186
5187static int
5188assemble_init(struct assembler *a, int nblocks, int firstlineno)
5189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 memset(a, 0, sizeof(struct assembler));
5191 a->a_lineno = firstlineno;
5192 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5193 if (!a->a_bytecode)
5194 return 0;
5195 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5196 if (!a->a_lnotab)
5197 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005198 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 PyErr_NoMemory();
5200 return 0;
5201 }
5202 a->a_postorder = (basicblock **)PyObject_Malloc(
5203 sizeof(basicblock *) * nblocks);
5204 if (!a->a_postorder) {
5205 PyErr_NoMemory();
5206 return 0;
5207 }
5208 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005209}
5210
5211static void
5212assemble_free(struct assembler *a)
5213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 Py_XDECREF(a->a_bytecode);
5215 Py_XDECREF(a->a_lnotab);
5216 if (a->a_postorder)
5217 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005218}
5219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220static int
5221blocksize(basicblock *b)
5222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 int i;
5224 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005227 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005229}
5230
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005231/* Appends a pair to the end of the line number table, a_lnotab, representing
5232 the instruction's bytecode offset and line number. See
5233 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005234
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005235static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005236assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005239 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005241
Serhiy Storchakaab874002016-09-11 13:48:15 +03005242 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 if(d_bytecode == 0 && d_lineno == 0)
5248 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 if (d_bytecode > 255) {
5251 int j, nbytes, ncodes = d_bytecode / 255;
5252 nbytes = a->a_lnotab_off + 2 * ncodes;
5253 len = PyBytes_GET_SIZE(a->a_lnotab);
5254 if (nbytes >= len) {
5255 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5256 len = nbytes;
5257 else if (len <= INT_MAX / 2)
5258 len *= 2;
5259 else {
5260 PyErr_NoMemory();
5261 return 0;
5262 }
5263 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5264 return 0;
5265 }
5266 lnotab = (unsigned char *)
5267 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5268 for (j = 0; j < ncodes; j++) {
5269 *lnotab++ = 255;
5270 *lnotab++ = 0;
5271 }
5272 d_bytecode -= ncodes * 255;
5273 a->a_lnotab_off += ncodes * 2;
5274 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005275 assert(0 <= d_bytecode && d_bytecode <= 255);
5276
5277 if (d_lineno < -128 || 127 < d_lineno) {
5278 int j, nbytes, ncodes, k;
5279 if (d_lineno < 0) {
5280 k = -128;
5281 /* use division on positive numbers */
5282 ncodes = (-d_lineno) / 128;
5283 }
5284 else {
5285 k = 127;
5286 ncodes = d_lineno / 127;
5287 }
5288 d_lineno -= ncodes * k;
5289 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 nbytes = a->a_lnotab_off + 2 * ncodes;
5291 len = PyBytes_GET_SIZE(a->a_lnotab);
5292 if (nbytes >= len) {
5293 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5294 len = nbytes;
5295 else if (len <= INT_MAX / 2)
5296 len *= 2;
5297 else {
5298 PyErr_NoMemory();
5299 return 0;
5300 }
5301 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5302 return 0;
5303 }
5304 lnotab = (unsigned char *)
5305 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5306 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005307 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 d_bytecode = 0;
5309 for (j = 1; j < ncodes; j++) {
5310 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005311 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 a->a_lnotab_off += ncodes * 2;
5314 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005315 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 len = PyBytes_GET_SIZE(a->a_lnotab);
5318 if (a->a_lnotab_off + 2 >= len) {
5319 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5320 return 0;
5321 }
5322 lnotab = (unsigned char *)
5323 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 a->a_lnotab_off += 2;
5326 if (d_bytecode) {
5327 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005328 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 }
5330 else { /* First line of a block; def stmt, etc. */
5331 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005332 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 }
5334 a->a_lineno = i->i_lineno;
5335 a->a_lineno_off = a->a_offset;
5336 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005337}
5338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005339/* assemble_emit()
5340 Extend the bytecode with a new instruction.
5341 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005342*/
5343
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005344static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005345assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005346{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005347 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005349 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005351 arg = i->i_oparg;
5352 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 if (i->i_lineno && !assemble_lnotab(a, i))
5354 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005355 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 if (len > PY_SSIZE_T_MAX / 2)
5357 return 0;
5358 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5359 return 0;
5360 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005361 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005363 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005365}
5366
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005367static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005371 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 /* Compute the size of each block and fixup jump args.
5375 Replace block pointer with position in bytecode. */
5376 do {
5377 totsize = 0;
5378 for (i = a->a_nblocks - 1; i >= 0; i--) {
5379 b = a->a_postorder[i];
5380 bsize = blocksize(b);
5381 b->b_offset = totsize;
5382 totsize += bsize;
5383 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005384 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5386 bsize = b->b_offset;
5387 for (i = 0; i < b->b_iused; i++) {
5388 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005389 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 /* Relative jumps are computed relative to
5391 the instruction pointer after fetching
5392 the jump instruction.
5393 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005394 bsize += isize;
5395 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005397 if (instr->i_jrel) {
5398 instr->i_oparg -= bsize;
5399 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005400 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005401 if (instrsize(instr->i_oparg) != isize) {
5402 extended_arg_recompile = 1;
5403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 }
5406 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 /* XXX: This is an awful hack that could hurt performance, but
5409 on the bright side it should work until we come up
5410 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 The issue is that in the first loop blocksize() is called
5413 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005414 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 So we loop until we stop seeing new EXTENDED_ARGs.
5418 The only EXTENDED_ARGs that could be popping up are
5419 ones in jump instructions. So this should converge
5420 fairly quickly.
5421 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005422 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005423}
5424
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005425static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005426dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005429 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 tuple = PyTuple_New(size);
5432 if (tuple == NULL)
5433 return NULL;
5434 while (PyDict_Next(dict, &pos, &k, &v)) {
5435 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005436 Py_INCREF(k);
5437 assert((i - offset) < size);
5438 assert((i - offset) >= 0);
5439 PyTuple_SET_ITEM(tuple, i - offset, k);
5440 }
5441 return tuple;
5442}
5443
5444static PyObject *
5445consts_dict_keys_inorder(PyObject *dict)
5446{
5447 PyObject *consts, *k, *v;
5448 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5449
5450 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5451 if (consts == NULL)
5452 return NULL;
5453 while (PyDict_Next(dict, &pos, &k, &v)) {
5454 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005455 /* The keys of the dictionary can be tuples wrapping a contant.
5456 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5457 * the object we want is always second. */
5458 if (PyTuple_CheckExact(k)) {
5459 k = PyTuple_GET_ITEM(k, 1);
5460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005462 assert(i < size);
5463 assert(i >= 0);
5464 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005466 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005467}
5468
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005469static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005470compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005473 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005475 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 if (ste->ste_nested)
5477 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005478 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005480 if (!ste->ste_generator && ste->ste_coroutine)
5481 flags |= CO_COROUTINE;
5482 if (ste->ste_generator && ste->ste_coroutine)
5483 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 if (ste->ste_varargs)
5485 flags |= CO_VARARGS;
5486 if (ste->ste_varkeywords)
5487 flags |= CO_VARKEYWORDS;
5488 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 /* (Only) inherit compilerflags in PyCF_MASK */
5491 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005494}
5495
INADA Naokic2e16072018-11-26 21:23:22 +09005496// Merge *tuple* with constant cache.
5497// Unlike merge_consts_recursive(), this function doesn't work recursively.
5498static int
5499merge_const_tuple(struct compiler *c, PyObject **tuple)
5500{
5501 assert(PyTuple_CheckExact(*tuple));
5502
5503 PyObject *key = _PyCode_ConstantKey(*tuple);
5504 if (key == NULL) {
5505 return 0;
5506 }
5507
5508 // t is borrowed reference
5509 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5510 Py_DECREF(key);
5511 if (t == NULL) {
5512 return 0;
5513 }
5514 if (t == key) { // tuple is new constant.
5515 return 1;
5516 }
5517
5518 PyObject *u = PyTuple_GET_ITEM(t, 1);
5519 Py_INCREF(u);
5520 Py_DECREF(*tuple);
5521 *tuple = u;
5522 return 1;
5523}
5524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005525static PyCodeObject *
5526makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 PyObject *tmp;
5529 PyCodeObject *co = NULL;
5530 PyObject *consts = NULL;
5531 PyObject *names = NULL;
5532 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 PyObject *name = NULL;
5534 PyObject *freevars = NULL;
5535 PyObject *cellvars = NULL;
5536 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005537 Py_ssize_t nlocals;
5538 int nlocals_int;
5539 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005540 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005541
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005542 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 names = dict_keys_inorder(c->u->u_names, 0);
5544 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5545 if (!consts || !names || !varnames)
5546 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5549 if (!cellvars)
5550 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005551 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 if (!freevars)
5553 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005554
INADA Naokic2e16072018-11-26 21:23:22 +09005555 if (!merge_const_tuple(c, &names) ||
5556 !merge_const_tuple(c, &varnames) ||
5557 !merge_const_tuple(c, &cellvars) ||
5558 !merge_const_tuple(c, &freevars))
5559 {
5560 goto error;
5561 }
5562
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005563 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005564 assert(nlocals < INT_MAX);
5565 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 flags = compute_code_flags(c);
5568 if (flags < 0)
5569 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5572 if (!bytecode)
5573 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5576 if (!tmp)
5577 goto error;
5578 Py_DECREF(consts);
5579 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005580 if (!merge_const_tuple(c, &consts)) {
5581 goto error;
5582 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583
Victor Stinnerf8e32212013-11-19 23:56:34 +01005584 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5585 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005586 maxdepth = stackdepth(c);
5587 if (maxdepth < 0) {
5588 goto error;
5589 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005590 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005591 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 bytecode, consts, names, varnames,
5593 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005594 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 c->u->u_firstlineno,
5596 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005597 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 Py_XDECREF(consts);
5599 Py_XDECREF(names);
5600 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 Py_XDECREF(name);
5602 Py_XDECREF(freevars);
5603 Py_XDECREF(cellvars);
5604 Py_XDECREF(bytecode);
5605 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005606}
5607
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005608
5609/* For debugging purposes only */
5610#if 0
5611static void
5612dump_instr(const struct instr *i)
5613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 const char *jrel = i->i_jrel ? "jrel " : "";
5615 const char *jabs = i->i_jabs ? "jabs " : "";
5616 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005619 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5623 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005624}
5625
5626static void
5627dump_basicblock(const basicblock *b)
5628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 const char *seen = b->b_seen ? "seen " : "";
5630 const char *b_return = b->b_return ? "return " : "";
5631 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5632 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5633 if (b->b_instr) {
5634 int i;
5635 for (i = 0; i < b->b_iused; i++) {
5636 fprintf(stderr, " [%02d] ", i);
5637 dump_instr(b->b_instr + i);
5638 }
5639 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005640}
5641#endif
5642
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005643static PyCodeObject *
5644assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 basicblock *b, *entryblock;
5647 struct assembler a;
5648 int i, j, nblocks;
5649 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 /* Make sure every block that falls off the end returns None.
5652 XXX NEXT_BLOCK() isn't quite right, because if the last
5653 block ends with a jump or return b_next shouldn't set.
5654 */
5655 if (!c->u->u_curblock->b_return) {
5656 NEXT_BLOCK(c);
5657 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005658 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 ADDOP(c, RETURN_VALUE);
5660 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 nblocks = 0;
5663 entryblock = NULL;
5664 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5665 nblocks++;
5666 entryblock = b;
5667 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 /* Set firstlineno if it wasn't explicitly set. */
5670 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005671 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5673 else
5674 c->u->u_firstlineno = 1;
5675 }
5676 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5677 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005678 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 /* Can't modify the bytecode after computing jump offsets. */
5681 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 /* Emit code in reverse postorder from dfs. */
5684 for (i = a.a_nblocks - 1; i >= 0; i--) {
5685 b = a.a_postorder[i];
5686 for (j = 0; j < b->b_iused; j++)
5687 if (!assemble_emit(&a, &b->b_instr[j]))
5688 goto error;
5689 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5692 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005693 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005697 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 assemble_free(&a);
5699 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005700}
Georg Brandl8334fd92010-12-04 10:26:46 +00005701
5702#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005703PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005704PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5705 PyArena *arena)
5706{
5707 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5708}