blob: 7d51819e00f0d96c39c53d8a7ca0af409393d876 [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 }
INADA Naokic2e16072018-11-26 21:23:22 +09001243
1244 return key;
1245}
1246
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001247static Py_ssize_t
1248compiler_add_const(struct compiler *c, PyObject *o)
1249{
INADA Naokic2e16072018-11-26 21:23:22 +09001250 PyObject *key = merge_consts_recursive(c, o);
1251 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001252 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001253 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001254
INADA Naokic2e16072018-11-26 21:23:22 +09001255 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1256 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258}
1259
1260static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001261compiler_addop_load_const(struct compiler *c, PyObject *o)
1262{
1263 Py_ssize_t arg = compiler_add_const(c, o);
1264 if (arg < 0)
1265 return 0;
1266 return compiler_addop_i(c, LOAD_CONST, arg);
1267}
1268
1269static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001273 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001275 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 return compiler_addop_i(c, opcode, arg);
1277}
1278
1279static int
1280compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001283 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1285 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 arg = compiler_add_o(c, dict, mangled);
1288 Py_DECREF(mangled);
1289 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001290 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291 return compiler_addop_i(c, opcode, arg);
1292}
1293
1294/* Add an opcode with an integer argument.
1295 Returns 0 on failure, 1 on success.
1296*/
1297
1298static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001299compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 struct instr *i;
1302 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001303
Victor Stinner2ad474b2016-03-01 23:34:47 +01001304 /* oparg value is unsigned, but a signed C int is usually used to store
1305 it in the C code (like Python/ceval.c).
1306
1307 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1308
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001309 The argument of a concrete bytecode instruction is limited to 8-bit.
1310 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1311 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001312 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 off = compiler_next_instr(c, c->u->u_curblock);
1315 if (off < 0)
1316 return 0;
1317 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001318 i->i_opcode = opcode;
1319 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 compiler_set_lineno(c, off);
1321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324static int
1325compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 struct instr *i;
1328 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001330 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 assert(b != NULL);
1332 off = compiler_next_instr(c, c->u->u_curblock);
1333 if (off < 0)
1334 return 0;
1335 i = &c->u->u_curblock->b_instr[off];
1336 i->i_opcode = opcode;
1337 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (absolute)
1339 i->i_jabs = 1;
1340 else
1341 i->i_jrel = 1;
1342 compiler_set_lineno(c, off);
1343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344}
1345
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001346/* NEXT_BLOCK() creates an implicit jump from the current block
1347 to the new block.
1348
1349 The returns inside this macro make it impossible to decref objects
1350 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (compiler_next_block((C)) == NULL) \
1354 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355}
1356
1357#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!compiler_addop((C), (OP))) \
1359 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360}
1361
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001362#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 if (!compiler_addop((C), (OP))) { \
1364 compiler_exit_scope(c); \
1365 return 0; \
1366 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001367}
1368
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001369#define ADDOP_LOAD_CONST(C, O) { \
1370 if (!compiler_addop_load_const((C), (O))) \
1371 return 0; \
1372}
1373
1374/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1375#define ADDOP_LOAD_CONST_NEW(C, O) { \
1376 PyObject *__new_const = (O); \
1377 if (__new_const == NULL) { \
1378 return 0; \
1379 } \
1380 if (!compiler_addop_load_const((C), __new_const)) { \
1381 Py_DECREF(__new_const); \
1382 return 0; \
1383 } \
1384 Py_DECREF(__new_const); \
1385}
1386
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1389 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390}
1391
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001392/* Same as ADDOP_O, but steals a reference. */
1393#define ADDOP_N(C, OP, O, TYPE) { \
1394 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1395 Py_DECREF((O)); \
1396 return 0; \
1397 } \
1398 Py_DECREF((O)); \
1399}
1400
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1403 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404}
1405
1406#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (!compiler_addop_i((C), (OP), (O))) \
1408 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409}
1410
1411#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (!compiler_addop_j((C), (OP), (O), 1)) \
1413 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414}
1415
1416#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (!compiler_addop_j((C), (OP), (O), 0)) \
1418 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419}
1420
1421/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1422 the ASDL name to synthesize the name of the C type and the visit function.
1423*/
1424
1425#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (!compiler_visit_ ## TYPE((C), (V))) \
1427 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428}
1429
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001430#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (!compiler_visit_ ## TYPE((C), (V))) { \
1432 compiler_exit_scope(c); \
1433 return 0; \
1434 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001435}
1436
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (!compiler_visit_slice((C), (V), (CTX))) \
1439 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 int _i; \
1444 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1445 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1446 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1447 if (!compiler_visit_ ## TYPE((C), elt)) \
1448 return 0; \
1449 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450}
1451
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001452#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 int _i; \
1454 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1455 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1456 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1457 if (!compiler_visit_ ## TYPE((C), elt)) { \
1458 compiler_exit_scope(c); \
1459 return 0; \
1460 } \
1461 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001462}
1463
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001464/* Search if variable annotations are present statically in a block. */
1465
1466static int
1467find_ann(asdl_seq *stmts)
1468{
1469 int i, j, res = 0;
1470 stmt_ty st;
1471
1472 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1473 st = (stmt_ty)asdl_seq_GET(stmts, i);
1474 switch (st->kind) {
1475 case AnnAssign_kind:
1476 return 1;
1477 case For_kind:
1478 res = find_ann(st->v.For.body) ||
1479 find_ann(st->v.For.orelse);
1480 break;
1481 case AsyncFor_kind:
1482 res = find_ann(st->v.AsyncFor.body) ||
1483 find_ann(st->v.AsyncFor.orelse);
1484 break;
1485 case While_kind:
1486 res = find_ann(st->v.While.body) ||
1487 find_ann(st->v.While.orelse);
1488 break;
1489 case If_kind:
1490 res = find_ann(st->v.If.body) ||
1491 find_ann(st->v.If.orelse);
1492 break;
1493 case With_kind:
1494 res = find_ann(st->v.With.body);
1495 break;
1496 case AsyncWith_kind:
1497 res = find_ann(st->v.AsyncWith.body);
1498 break;
1499 case Try_kind:
1500 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1501 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1502 st->v.Try.handlers, j);
1503 if (find_ann(handler->v.ExceptHandler.body)) {
1504 return 1;
1505 }
1506 }
1507 res = find_ann(st->v.Try.body) ||
1508 find_ann(st->v.Try.finalbody) ||
1509 find_ann(st->v.Try.orelse);
1510 break;
1511 default:
1512 res = 0;
1513 }
1514 if (res) {
1515 break;
1516 }
1517 }
1518 return res;
1519}
1520
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001521/*
1522 * Frame block handling functions
1523 */
1524
1525static int
1526compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1527 basicblock *exit)
1528{
1529 struct fblockinfo *f;
1530 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1531 PyErr_SetString(PyExc_SyntaxError,
1532 "too many statically nested blocks");
1533 return 0;
1534 }
1535 f = &c->u->u_fblock[c->u->u_nfblocks++];
1536 f->fb_type = t;
1537 f->fb_block = b;
1538 f->fb_exit = exit;
1539 return 1;
1540}
1541
1542static void
1543compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1544{
1545 struct compiler_unit *u = c->u;
1546 assert(u->u_nfblocks > 0);
1547 u->u_nfblocks--;
1548 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1549 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1550}
1551
1552/* Unwind a frame block. If preserve_tos is true, the TOS before
1553 * popping the blocks will be restored afterwards.
1554 */
1555static int
1556compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1557 int preserve_tos)
1558{
1559 switch (info->fb_type) {
1560 case WHILE_LOOP:
1561 return 1;
1562
1563 case FINALLY_END:
1564 ADDOP_I(c, POP_FINALLY, preserve_tos);
1565 return 1;
1566
1567 case FOR_LOOP:
1568 /* Pop the iterator */
1569 if (preserve_tos) {
1570 ADDOP(c, ROT_TWO);
1571 }
1572 ADDOP(c, POP_TOP);
1573 return 1;
1574
1575 case EXCEPT:
1576 ADDOP(c, POP_BLOCK);
1577 return 1;
1578
1579 case FINALLY_TRY:
1580 ADDOP(c, POP_BLOCK);
1581 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1582 return 1;
1583
1584 case WITH:
1585 case ASYNC_WITH:
1586 ADDOP(c, POP_BLOCK);
1587 if (preserve_tos) {
1588 ADDOP(c, ROT_TWO);
1589 }
1590 ADDOP(c, BEGIN_FINALLY);
1591 ADDOP(c, WITH_CLEANUP_START);
1592 if (info->fb_type == ASYNC_WITH) {
1593 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001594 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001595 ADDOP(c, YIELD_FROM);
1596 }
1597 ADDOP(c, WITH_CLEANUP_FINISH);
1598 ADDOP_I(c, POP_FINALLY, 0);
1599 return 1;
1600
1601 case HANDLER_CLEANUP:
1602 if (preserve_tos) {
1603 ADDOP(c, ROT_FOUR);
1604 }
1605 if (info->fb_exit) {
1606 ADDOP(c, POP_BLOCK);
1607 ADDOP(c, POP_EXCEPT);
1608 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1609 }
1610 else {
1611 ADDOP(c, POP_EXCEPT);
1612 }
1613 return 1;
1614 }
1615 Py_UNREACHABLE();
1616}
1617
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001618/* Compile a sequence of statements, checking for a docstring
1619 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620
1621static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001622compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001624 int i = 0;
1625 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001626 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001627
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001628 /* Set current line number to the line number of first statement.
1629 This way line number for SETUP_ANNOTATIONS will always
1630 coincide with the line number of first "real" statement in module.
1631 If body is empy, then lineno will be set later in assemble. */
1632 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1633 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001634 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001635 c->u->u_lineno = st->lineno;
1636 }
1637 /* Every annotated class and module should have __annotations__. */
1638 if (find_ann(stmts)) {
1639 ADDOP(c, SETUP_ANNOTATIONS);
1640 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001641 if (!asdl_seq_LEN(stmts))
1642 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001643 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001644 if (c->c_optimize < 2) {
1645 docstring = _PyAST_GetDocString(stmts);
1646 if (docstring) {
1647 i = 1;
1648 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1649 assert(st->kind == Expr_kind);
1650 VISIT(c, expr, st->v.Expr.value);
1651 if (!compiler_nameop(c, __doc__, Store))
1652 return 0;
1653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001655 for (; i < asdl_seq_LEN(stmts); i++)
1656 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658}
1659
1660static PyCodeObject *
1661compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyCodeObject *co;
1664 int addNone = 1;
1665 static PyObject *module;
1666 if (!module) {
1667 module = PyUnicode_InternFromString("<module>");
1668 if (!module)
1669 return NULL;
1670 }
1671 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001672 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 return NULL;
1674 switch (mod->kind) {
1675 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001676 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 compiler_exit_scope(c);
1678 return 0;
1679 }
1680 break;
1681 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001682 if (find_ann(mod->v.Interactive.body)) {
1683 ADDOP(c, SETUP_ANNOTATIONS);
1684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 c->c_interactive = 1;
1686 VISIT_SEQ_IN_SCOPE(c, stmt,
1687 mod->v.Interactive.body);
1688 break;
1689 case Expression_kind:
1690 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1691 addNone = 0;
1692 break;
1693 case Suite_kind:
1694 PyErr_SetString(PyExc_SystemError,
1695 "suite should not be possible");
1696 return 0;
1697 default:
1698 PyErr_Format(PyExc_SystemError,
1699 "module kind %d should not be possible",
1700 mod->kind);
1701 return 0;
1702 }
1703 co = assemble(c, addNone);
1704 compiler_exit_scope(c);
1705 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001706}
1707
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708/* The test for LOCAL must come before the test for FREE in order to
1709 handle classes where name is both local and free. The local var is
1710 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001711*/
1712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713static int
1714get_ref_type(struct compiler *c, PyObject *name)
1715{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001716 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001717 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001718 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001719 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001720 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (scope == 0) {
1722 char buf[350];
1723 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001724 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001726 PyUnicode_AsUTF8(name),
1727 PyUnicode_AsUTF8(c->u->u_name),
1728 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1729 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1730 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1731 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 );
1733 Py_FatalError(buf);
1734 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737}
1738
1739static int
1740compiler_lookup_arg(PyObject *dict, PyObject *name)
1741{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001742 PyObject *v;
1743 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001744 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001745 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001746 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747}
1748
1749static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001750compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001752 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001753 if (qualname == NULL)
1754 qualname = co->co_name;
1755
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001756 if (free) {
1757 for (i = 0; i < free; ++i) {
1758 /* Bypass com_addop_varname because it will generate
1759 LOAD_DEREF but LOAD_CLOSURE is needed.
1760 */
1761 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1762 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001764 /* Special case: If a class contains a method with a
1765 free variable that has the same name as a method,
1766 the name will be considered free *and* local in the
1767 class. It should be handled by the closure, as
1768 well as by the normal name loookup logic.
1769 */
1770 reftype = get_ref_type(c, name);
1771 if (reftype == CELL)
1772 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1773 else /* (reftype == FREE) */
1774 arg = compiler_lookup_arg(c->u->u_freevars, name);
1775 if (arg == -1) {
1776 fprintf(stderr,
1777 "lookup %s in %s %d %d\n"
1778 "freevars of %s: %s\n",
1779 PyUnicode_AsUTF8(PyObject_Repr(name)),
1780 PyUnicode_AsUTF8(c->u->u_name),
1781 reftype, arg,
1782 PyUnicode_AsUTF8(co->co_name),
1783 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1784 Py_FatalError("compiler_make_closure()");
1785 }
1786 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001788 flags |= 0x08;
1789 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001791 ADDOP_LOAD_CONST(c, (PyObject*)co);
1792 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001793 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795}
1796
1797static int
1798compiler_decorators(struct compiler *c, asdl_seq* decos)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (!decos)
1803 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1806 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1807 }
1808 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809}
1810
1811static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001812compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001814{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001815 /* Push a dict of keyword-only default values.
1816
1817 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1818 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001819 int i;
1820 PyObject *keys = NULL;
1821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1823 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1824 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1825 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001826 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001827 if (!mangled) {
1828 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001830 if (keys == NULL) {
1831 keys = PyList_New(1);
1832 if (keys == NULL) {
1833 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001834 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001835 }
1836 PyList_SET_ITEM(keys, 0, mangled);
1837 }
1838 else {
1839 int res = PyList_Append(keys, mangled);
1840 Py_DECREF(mangled);
1841 if (res == -1) {
1842 goto error;
1843 }
1844 }
1845 if (!compiler_visit_expr(c, default_)) {
1846 goto error;
1847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
1849 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001850 if (keys != NULL) {
1851 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1852 PyObject *keys_tuple = PyList_AsTuple(keys);
1853 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001854 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001855 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001856 assert(default_count > 0);
1857 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001858 }
1859 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001860 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001861 }
1862
1863error:
1864 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001865 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001866}
1867
1868static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001869compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1870{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001871 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001872 return 1;
1873}
1874
1875static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001876compiler_visit_argannotation(struct compiler *c, identifier id,
1877 expr_ty annotation, PyObject *names)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001880 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001881 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1882 VISIT(c, annexpr, annotation)
1883 }
1884 else {
1885 VISIT(c, expr, annotation);
1886 }
Victor Stinner065efc32014-02-18 22:07:56 +01001887 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001888 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001889 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001890 if (PyList_Append(names, mangled) < 0) {
1891 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001892 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001893 }
1894 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001896 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001897}
1898
1899static int
1900compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1901 PyObject *names)
1902{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001903 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 for (i = 0; i < asdl_seq_LEN(args); i++) {
1905 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001906 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 c,
1908 arg->arg,
1909 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001910 names))
1911 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001913 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001914}
1915
1916static int
1917compiler_visit_annotations(struct compiler *c, arguments_ty args,
1918 expr_ty returns)
1919{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001920 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001922
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001923 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 */
1925 static identifier return_str;
1926 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001927 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 names = PyList_New(0);
1929 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001930 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001931
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001932 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001934 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001935 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001936 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001938 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001940 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001941 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001942 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (!return_str) {
1946 return_str = PyUnicode_InternFromString("return");
1947 if (!return_str)
1948 goto error;
1949 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001950 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 goto error;
1952 }
1953
1954 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001956 PyObject *keytuple = PyList_AsTuple(names);
1957 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001958 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001959 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001960 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001962 else {
1963 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001964 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001966
1967error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001969 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001970}
1971
1972static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001973compiler_visit_defaults(struct compiler *c, arguments_ty args)
1974{
1975 VISIT_SEQ(c, expr, args->defaults);
1976 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1977 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978}
1979
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980static Py_ssize_t
1981compiler_default_arguments(struct compiler *c, arguments_ty args)
1982{
1983 Py_ssize_t funcflags = 0;
1984 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001985 if (!compiler_visit_defaults(c, args))
1986 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 funcflags |= 0x01;
1988 }
1989 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001992 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001993 return -1;
1994 }
1995 else if (res > 0) {
1996 funcflags |= 0x02;
1997 }
1998 }
1999 return funcflags;
2000}
2001
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002static int
Yury Selivanov75445082015-05-11 22:57:16 -04002003compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002006 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002007 arguments_ty args;
2008 expr_ty returns;
2009 identifier name;
2010 asdl_seq* decos;
2011 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002012 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002013 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002014 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002015 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Yury Selivanov75445082015-05-11 22:57:16 -04002017 if (is_async) {
2018 assert(s->kind == AsyncFunctionDef_kind);
2019
2020 args = s->v.AsyncFunctionDef.args;
2021 returns = s->v.AsyncFunctionDef.returns;
2022 decos = s->v.AsyncFunctionDef.decorator_list;
2023 name = s->v.AsyncFunctionDef.name;
2024 body = s->v.AsyncFunctionDef.body;
2025
2026 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2027 } else {
2028 assert(s->kind == FunctionDef_kind);
2029
2030 args = s->v.FunctionDef.args;
2031 returns = s->v.FunctionDef.returns;
2032 decos = s->v.FunctionDef.decorator_list;
2033 name = s->v.FunctionDef.name;
2034 body = s->v.FunctionDef.body;
2035
2036 scope_type = COMPILER_SCOPE_FUNCTION;
2037 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (!compiler_decorators(c, decos))
2040 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002041
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002042 firstlineno = s->lineno;
2043 if (asdl_seq_LEN(decos)) {
2044 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2045 }
2046
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002047 funcflags = compiler_default_arguments(c, args);
2048 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002050 }
2051
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002052 annotations = compiler_visit_annotations(c, args, returns);
2053 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002054 return 0;
2055 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002056 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002057 funcflags |= 0x04;
2058 }
2059
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002060 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002061 return 0;
2062 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063
INADA Naokicb41b272017-02-23 00:31:59 +09002064 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002065 if (c->c_optimize < 2) {
2066 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002067 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002068 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 compiler_exit_scope(c);
2070 return 0;
2071 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 c->u->u_argcount = asdl_seq_LEN(args->args);
2074 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002075 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002077 qualname = c->u->u_qualname;
2078 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002080 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002081 Py_XDECREF(qualname);
2082 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002084 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002086 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002087 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 /* decorators */
2091 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2092 ADDOP_I(c, CALL_FUNCTION, 1);
2093 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094
Yury Selivanov75445082015-05-11 22:57:16 -04002095 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096}
2097
2098static int
2099compiler_class(struct compiler *c, stmt_ty s)
2100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 PyCodeObject *co;
2102 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002103 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (!compiler_decorators(c, decos))
2107 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002108
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002109 firstlineno = s->lineno;
2110 if (asdl_seq_LEN(decos)) {
2111 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2112 }
2113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* ultimately generate code for:
2115 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2116 where:
2117 <func> is a function/closure created from the class body;
2118 it has a single argument (__locals__) where the dict
2119 (or MutableSequence) representing the locals is passed
2120 <name> is the class name
2121 <bases> is the positional arguments and *varargs argument
2122 <keywords> is the keyword arguments and **kwds argument
2123 This borrows from compiler_call.
2124 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002127 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002128 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 return 0;
2130 /* this block represents what we do in the new scope */
2131 {
2132 /* use the class name for name mangling */
2133 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002134 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* load (global) __name__ ... */
2136 str = PyUnicode_InternFromString("__name__");
2137 if (!str || !compiler_nameop(c, str, Load)) {
2138 Py_XDECREF(str);
2139 compiler_exit_scope(c);
2140 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_DECREF(str);
2143 /* ... and store it as __module__ */
2144 str = PyUnicode_InternFromString("__module__");
2145 if (!str || !compiler_nameop(c, str, Store)) {
2146 Py_XDECREF(str);
2147 compiler_exit_scope(c);
2148 return 0;
2149 }
2150 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002151 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002152 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002153 str = PyUnicode_InternFromString("__qualname__");
2154 if (!str || !compiler_nameop(c, str, Store)) {
2155 Py_XDECREF(str);
2156 compiler_exit_scope(c);
2157 return 0;
2158 }
2159 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002161 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 compiler_exit_scope(c);
2163 return 0;
2164 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002165 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002166 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002167 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002168 str = PyUnicode_InternFromString("__class__");
2169 if (str == NULL) {
2170 compiler_exit_scope(c);
2171 return 0;
2172 }
2173 i = compiler_lookup_arg(c->u->u_cellvars, str);
2174 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002175 if (i < 0) {
2176 compiler_exit_scope(c);
2177 return 0;
2178 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002179 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002182 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002183 str = PyUnicode_InternFromString("__classcell__");
2184 if (!str || !compiler_nameop(c, str, Store)) {
2185 Py_XDECREF(str);
2186 compiler_exit_scope(c);
2187 return 0;
2188 }
2189 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002191 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002192 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002193 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002194 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002195 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002196 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* create the code object */
2198 co = assemble(c, 1);
2199 }
2200 /* leave the new scope */
2201 compiler_exit_scope(c);
2202 if (co == NULL)
2203 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* 2. load the 'build_class' function */
2206 ADDOP(c, LOAD_BUILD_CLASS);
2207
2208 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002209 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 Py_DECREF(co);
2211
2212 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002213 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214
2215 /* 5. generate the rest of the code for the call */
2216 if (!compiler_call_helper(c, 2,
2217 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002218 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 return 0;
2220
2221 /* 6. apply decorators */
2222 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2223 ADDOP_I(c, CALL_FUNCTION, 1);
2224 }
2225
2226 /* 7. store into <name> */
2227 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2228 return 0;
2229 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002230}
2231
2232static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002233cmpop(cmpop_ty op)
2234{
2235 switch (op) {
2236 case Eq:
2237 return PyCmp_EQ;
2238 case NotEq:
2239 return PyCmp_NE;
2240 case Lt:
2241 return PyCmp_LT;
2242 case LtE:
2243 return PyCmp_LE;
2244 case Gt:
2245 return PyCmp_GT;
2246 case GtE:
2247 return PyCmp_GE;
2248 case Is:
2249 return PyCmp_IS;
2250 case IsNot:
2251 return PyCmp_IS_NOT;
2252 case In:
2253 return PyCmp_IN;
2254 case NotIn:
2255 return PyCmp_NOT_IN;
2256 default:
2257 return PyCmp_BAD;
2258 }
2259}
2260
2261static int
2262compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2263{
2264 switch (e->kind) {
2265 case UnaryOp_kind:
2266 if (e->v.UnaryOp.op == Not)
2267 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2268 /* fallback to general implementation */
2269 break;
2270 case BoolOp_kind: {
2271 asdl_seq *s = e->v.BoolOp.values;
2272 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2273 assert(n >= 0);
2274 int cond2 = e->v.BoolOp.op == Or;
2275 basicblock *next2 = next;
2276 if (!cond2 != !cond) {
2277 next2 = compiler_new_block(c);
2278 if (next2 == NULL)
2279 return 0;
2280 }
2281 for (i = 0; i < n; ++i) {
2282 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2283 return 0;
2284 }
2285 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2286 return 0;
2287 if (next2 != next)
2288 compiler_use_next_block(c, next2);
2289 return 1;
2290 }
2291 case IfExp_kind: {
2292 basicblock *end, *next2;
2293 end = compiler_new_block(c);
2294 if (end == NULL)
2295 return 0;
2296 next2 = compiler_new_block(c);
2297 if (next2 == NULL)
2298 return 0;
2299 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2300 return 0;
2301 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2302 return 0;
2303 ADDOP_JREL(c, JUMP_FORWARD, end);
2304 compiler_use_next_block(c, next2);
2305 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2306 return 0;
2307 compiler_use_next_block(c, end);
2308 return 1;
2309 }
2310 case Compare_kind: {
2311 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2312 if (n > 0) {
2313 basicblock *cleanup = compiler_new_block(c);
2314 if (cleanup == NULL)
2315 return 0;
2316 VISIT(c, expr, e->v.Compare.left);
2317 for (i = 0; i < n; i++) {
2318 VISIT(c, expr,
2319 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2320 ADDOP(c, DUP_TOP);
2321 ADDOP(c, ROT_THREE);
2322 ADDOP_I(c, COMPARE_OP,
2323 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2324 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2325 NEXT_BLOCK(c);
2326 }
2327 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2328 ADDOP_I(c, COMPARE_OP,
2329 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2330 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2331 basicblock *end = compiler_new_block(c);
2332 if (end == NULL)
2333 return 0;
2334 ADDOP_JREL(c, JUMP_FORWARD, end);
2335 compiler_use_next_block(c, cleanup);
2336 ADDOP(c, POP_TOP);
2337 if (!cond) {
2338 ADDOP_JREL(c, JUMP_FORWARD, next);
2339 }
2340 compiler_use_next_block(c, end);
2341 return 1;
2342 }
2343 /* fallback to general implementation */
2344 break;
2345 }
2346 default:
2347 /* fallback to general implementation */
2348 break;
2349 }
2350
2351 /* general implementation */
2352 VISIT(c, expr, e);
2353 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2354 return 1;
2355}
2356
2357static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002358compiler_ifexp(struct compiler *c, expr_ty e)
2359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 basicblock *end, *next;
2361
2362 assert(e->kind == IfExp_kind);
2363 end = compiler_new_block(c);
2364 if (end == NULL)
2365 return 0;
2366 next = compiler_new_block(c);
2367 if (next == NULL)
2368 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002369 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2370 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 VISIT(c, expr, e->v.IfExp.body);
2372 ADDOP_JREL(c, JUMP_FORWARD, end);
2373 compiler_use_next_block(c, next);
2374 VISIT(c, expr, e->v.IfExp.orelse);
2375 compiler_use_next_block(c, end);
2376 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002377}
2378
2379static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380compiler_lambda(struct compiler *c, expr_ty e)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002383 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002385 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 arguments_ty args = e->v.Lambda.args;
2387 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 if (!name) {
2390 name = PyUnicode_InternFromString("<lambda>");
2391 if (!name)
2392 return 0;
2393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002395 funcflags = compiler_default_arguments(c, args);
2396 if (funcflags == -1) {
2397 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002399
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002400 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002401 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Make None the first constant, so the lambda can't have a
2405 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002406 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 c->u->u_argcount = asdl_seq_LEN(args->args);
2410 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2411 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2412 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002413 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 }
2415 else {
2416 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002417 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002419 qualname = c->u->u_qualname;
2420 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002422 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002425 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002426 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 Py_DECREF(co);
2428
2429 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002430}
2431
2432static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433compiler_if(struct compiler *c, stmt_ty s)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 basicblock *end, *next;
2436 int constant;
2437 assert(s->kind == If_kind);
2438 end = compiler_new_block(c);
2439 if (end == NULL)
2440 return 0;
2441
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002442 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 /* constant = 0: "if 0"
2444 * constant = 1: "if 1", "if 2", ...
2445 * constant = -1: rest */
2446 if (constant == 0) {
2447 if (s->v.If.orelse)
2448 VISIT_SEQ(c, stmt, s->v.If.orelse);
2449 } else if (constant == 1) {
2450 VISIT_SEQ(c, stmt, s->v.If.body);
2451 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002452 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 next = compiler_new_block(c);
2454 if (next == NULL)
2455 return 0;
2456 }
2457 else
2458 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002459 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2460 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002462 if (asdl_seq_LEN(s->v.If.orelse)) {
2463 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 compiler_use_next_block(c, next);
2465 VISIT_SEQ(c, stmt, s->v.If.orelse);
2466 }
2467 }
2468 compiler_use_next_block(c, end);
2469 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470}
2471
2472static int
2473compiler_for(struct compiler *c, stmt_ty s)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 start = compiler_new_block(c);
2478 cleanup = compiler_new_block(c);
2479 end = compiler_new_block(c);
2480 if (start == NULL || end == NULL || cleanup == NULL)
2481 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002482
2483 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 VISIT(c, expr, s->v.For.iter);
2487 ADDOP(c, GET_ITER);
2488 compiler_use_next_block(c, start);
2489 ADDOP_JREL(c, FOR_ITER, cleanup);
2490 VISIT(c, expr, s->v.For.target);
2491 VISIT_SEQ(c, stmt, s->v.For.body);
2492 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2493 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002494
2495 compiler_pop_fblock(c, FOR_LOOP, start);
2496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 VISIT_SEQ(c, stmt, s->v.For.orelse);
2498 compiler_use_next_block(c, end);
2499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500}
2501
Yury Selivanov75445082015-05-11 22:57:16 -04002502
2503static int
2504compiler_async_for(struct compiler *c, stmt_ty s)
2505{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002506 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002507 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2508 return compiler_error(c, "'async for' outside async function");
2509 }
2510
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002511 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002512 except = compiler_new_block(c);
2513 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002514
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002515 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002516 return 0;
2517
2518 VISIT(c, expr, s->v.AsyncFor.iter);
2519 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002520
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002521 compiler_use_next_block(c, start);
2522 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2523 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002524
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002525 /* SETUP_FINALLY to guard the __anext__ call */
2526 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002527 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002528 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002529 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002530 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002531
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002532 /* Success block for __anext__ */
2533 VISIT(c, expr, s->v.AsyncFor.target);
2534 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2535 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2536
2537 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002538
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002539 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002540 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002541 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002542
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002543 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002544 VISIT_SEQ(c, stmt, s->v.For.orelse);
2545
2546 compiler_use_next_block(c, end);
2547
2548 return 1;
2549}
2550
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002551static int
2552compiler_while(struct compiler *c, stmt_ty s)
2553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002555 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (constant == 0) {
2558 if (s->v.While.orelse)
2559 VISIT_SEQ(c, stmt, s->v.While.orelse);
2560 return 1;
2561 }
2562 loop = compiler_new_block(c);
2563 end = compiler_new_block(c);
2564 if (constant == -1) {
2565 anchor = compiler_new_block(c);
2566 if (anchor == NULL)
2567 return 0;
2568 }
2569 if (loop == NULL || end == NULL)
2570 return 0;
2571 if (s->v.While.orelse) {
2572 orelse = compiler_new_block(c);
2573 if (orelse == NULL)
2574 return 0;
2575 }
2576 else
2577 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002580 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return 0;
2582 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002583 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2584 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 }
2586 VISIT_SEQ(c, stmt, s->v.While.body);
2587 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* XXX should the two POP instructions be in a separate block
2590 if there is no else clause ?
2591 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002593 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002595 compiler_pop_fblock(c, WHILE_LOOP, loop);
2596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 if (orelse != NULL) /* what if orelse is just pass? */
2598 VISIT_SEQ(c, stmt, s->v.While.orelse);
2599 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602}
2603
2604static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002605compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002607 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002608 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002609 if (c->u->u_ste->ste_type != FunctionBlock)
2610 return compiler_error(c, "'return' outside function");
2611 if (s->v.Return.value != NULL &&
2612 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2613 {
2614 return compiler_error(
2615 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002617 if (preserve_tos) {
2618 VISIT(c, expr, s->v.Return.value);
2619 }
2620 for (int depth = c->u->u_nfblocks; depth--;) {
2621 struct fblockinfo *info = &c->u->u_fblock[depth];
2622
2623 if (!compiler_unwind_fblock(c, info, preserve_tos))
2624 return 0;
2625 }
2626 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002627 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002628 }
2629 else if (!preserve_tos) {
2630 VISIT(c, expr, s->v.Return.value);
2631 }
2632 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635}
2636
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002637static int
2638compiler_break(struct compiler *c)
2639{
2640 for (int depth = c->u->u_nfblocks; depth--;) {
2641 struct fblockinfo *info = &c->u->u_fblock[depth];
2642
2643 if (!compiler_unwind_fblock(c, info, 0))
2644 return 0;
2645 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2646 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2647 return 1;
2648 }
2649 }
2650 return compiler_error(c, "'break' outside loop");
2651}
2652
2653static int
2654compiler_continue(struct compiler *c)
2655{
2656 for (int depth = c->u->u_nfblocks; depth--;) {
2657 struct fblockinfo *info = &c->u->u_fblock[depth];
2658
2659 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2660 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2661 return 1;
2662 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002663 if (!compiler_unwind_fblock(c, info, 0))
2664 return 0;
2665 }
2666 return compiler_error(c, "'continue' not properly in loop");
2667}
2668
2669
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671
2672 SETUP_FINALLY L
2673 <code for body>
2674 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002675 BEGIN_FINALLY
2676 L:
2677 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 END_FINALLY
2679
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 The special instructions use the block stack. Each block
2681 stack entry contains the instruction that created it (here
2682 SETUP_FINALLY), the level of the value stack at the time the
2683 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 Pushes the current value stack level and the label
2687 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002689 Pops en entry from the block stack.
2690 BEGIN_FINALLY
2691 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002693 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2694 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002697 when a SETUP_FINALLY entry is found, the raised and the caught
2698 exceptions are pushed onto the value stack (and the exception
2699 condition is cleared), and the interpreter jumps to the label
2700 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701*/
2702
2703static int
2704compiler_try_finally(struct compiler *c, stmt_ty s)
2705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 body = compiler_new_block(c);
2709 end = compiler_new_block(c);
2710 if (body == NULL || end == NULL)
2711 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002713 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 ADDOP_JREL(c, SETUP_FINALLY, end);
2715 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002716 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002718 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2719 if (!compiler_try_except(c, s))
2720 return 0;
2721 }
2722 else {
2723 VISIT_SEQ(c, stmt, s->v.Try.body);
2724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002726 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002729 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002731 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002733 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 ADDOP(c, END_FINALLY);
2735 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737}
2738
2739/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002740 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 (The contents of the value stack is shown in [], with the top
2742 at the right; 'tb' is trace-back info, 'val' the exception's
2743 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744
2745 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002746 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 [] <code for S>
2748 [] POP_BLOCK
2749 [] JUMP_FORWARD L0
2750
2751 [tb, val, exc] L1: DUP )
2752 [tb, val, exc, exc] <evaluate E1> )
2753 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2754 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2755 [tb, val, exc] POP
2756 [tb, val] <assign to V1> (or POP if no V1)
2757 [tb] POP
2758 [] <code for S1>
2759 JUMP_FORWARD L0
2760
2761 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762 .............................etc.......................
2763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2765
2766 [] L0: <next statement>
2767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768 Of course, parts are not generated if Vi or Ei is not present.
2769*/
2770static int
2771compiler_try_except(struct compiler *c, stmt_ty s)
2772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002774 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 body = compiler_new_block(c);
2777 except = compiler_new_block(c);
2778 orelse = compiler_new_block(c);
2779 end = compiler_new_block(c);
2780 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2781 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002782 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002786 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 ADDOP(c, POP_BLOCK);
2788 compiler_pop_fblock(c, EXCEPT, body);
2789 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002790 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 compiler_use_next_block(c, except);
2792 for (i = 0; i < n; i++) {
2793 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002794 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 if (!handler->v.ExceptHandler.type && i < n-1)
2796 return compiler_error(c, "default 'except:' must be last");
2797 c->u->u_lineno_set = 0;
2798 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002799 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 except = compiler_new_block(c);
2801 if (except == NULL)
2802 return 0;
2803 if (handler->v.ExceptHandler.type) {
2804 ADDOP(c, DUP_TOP);
2805 VISIT(c, expr, handler->v.ExceptHandler.type);
2806 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2807 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2808 }
2809 ADDOP(c, POP_TOP);
2810 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002811 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002812
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002813 cleanup_end = compiler_new_block(c);
2814 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002815 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002816 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002817 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002818
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002819 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2820 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002822 /*
2823 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002824 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002825 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002826 try:
2827 # body
2828 finally:
2829 name = None
2830 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002831 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002833 /* second try: */
2834 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2835 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002836 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002837 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002839 /* second # body */
2840 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2841 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002842 ADDOP(c, BEGIN_FINALLY);
2843 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002845 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002846 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002847 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002848 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002851 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002852 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002853 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002855 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002856 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002857 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 }
2859 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002860 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002862 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002863 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002864 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865
Guido van Rossumb940e112007-01-10 16:19:56 +00002866 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002867 ADDOP(c, POP_TOP);
2868 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002869 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002870 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002872 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 }
2875 ADDOP_JREL(c, JUMP_FORWARD, end);
2876 compiler_use_next_block(c, except);
2877 }
2878 ADDOP(c, END_FINALLY);
2879 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002880 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 compiler_use_next_block(c, end);
2882 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883}
2884
2885static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002886compiler_try(struct compiler *c, stmt_ty s) {
2887 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2888 return compiler_try_finally(c, s);
2889 else
2890 return compiler_try_except(c, s);
2891}
2892
2893
2894static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895compiler_import_as(struct compiler *c, identifier name, identifier asname)
2896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 /* The IMPORT_NAME opcode was already generated. This function
2898 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002901 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002903 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2904 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002905 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002906 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002909 while (1) {
2910 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002912 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002913 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002914 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002915 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002917 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002918 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002919 if (dot == -1) {
2920 break;
2921 }
2922 ADDOP(c, ROT_TWO);
2923 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002925 if (!compiler_nameop(c, asname, Store)) {
2926 return 0;
2927 }
2928 ADDOP(c, POP_TOP);
2929 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 }
2931 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932}
2933
2934static int
2935compiler_import(struct compiler *c, stmt_ty s)
2936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 /* The Import node stores a module name like a.b.c as a single
2938 string. This is convenient for all cases except
2939 import a.b.c as d
2940 where we need to parse that string to extract the individual
2941 module names.
2942 XXX Perhaps change the representation to make this case simpler?
2943 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002944 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 for (i = 0; i < n; i++) {
2947 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2948 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002950 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2951 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 if (alias->asname) {
2955 r = compiler_import_as(c, alias->name, alias->asname);
2956 if (!r)
2957 return r;
2958 }
2959 else {
2960 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002961 Py_ssize_t dot = PyUnicode_FindChar(
2962 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002963 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002964 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002965 if (tmp == NULL)
2966 return 0;
2967 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 Py_DECREF(tmp);
2971 }
2972 if (!r)
2973 return r;
2974 }
2975 }
2976 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977}
2978
2979static int
2980compiler_from_import(struct compiler *c, stmt_ty s)
2981{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002982 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002983 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 if (!empty_string) {
2987 empty_string = PyUnicode_FromString("");
2988 if (!empty_string)
2989 return 0;
2990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002992 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002993
2994 names = PyTuple_New(n);
2995 if (!names)
2996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 /* build up the names */
2999 for (i = 0; i < n; i++) {
3000 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3001 Py_INCREF(alias->name);
3002 PyTuple_SET_ITEM(names, i, alias->name);
3003 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003006 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 Py_DECREF(names);
3008 return compiler_error(c, "from __future__ imports must occur "
3009 "at the beginning of the file");
3010 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003011 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 if (s->v.ImportFrom.module) {
3014 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3015 }
3016 else {
3017 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3018 }
3019 for (i = 0; i < n; i++) {
3020 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3021 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003023 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 assert(n == 1);
3025 ADDOP(c, IMPORT_STAR);
3026 return 1;
3027 }
3028
3029 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3030 store_name = alias->name;
3031 if (alias->asname)
3032 store_name = alias->asname;
3033
3034 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 return 0;
3036 }
3037 }
3038 /* remove imported module */
3039 ADDOP(c, POP_TOP);
3040 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041}
3042
3043static int
3044compiler_assert(struct compiler *c, stmt_ty s)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 static PyObject *assertion_error = NULL;
3047 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048
Georg Brandl8334fd92010-12-04 10:26:46 +00003049 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 return 1;
3051 if (assertion_error == NULL) {
3052 assertion_error = PyUnicode_InternFromString("AssertionError");
3053 if (assertion_error == NULL)
3054 return 0;
3055 }
3056 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003057 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3058 {
3059 if (!compiler_warn(c, "assertion is always true, "
3060 "perhaps remove parentheses?"))
3061 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003062 return 0;
3063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 end = compiler_new_block(c);
3066 if (end == NULL)
3067 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003068 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3069 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3071 if (s->v.Assert.msg) {
3072 VISIT(c, expr, s->v.Assert.msg);
3073 ADDOP_I(c, CALL_FUNCTION, 1);
3074 }
3075 ADDOP_I(c, RAISE_VARARGS, 1);
3076 compiler_use_next_block(c, end);
3077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078}
3079
3080static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003081compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3082{
3083 if (c->c_interactive && c->c_nestlevel <= 1) {
3084 VISIT(c, expr, value);
3085 ADDOP(c, PRINT_EXPR);
3086 return 1;
3087 }
3088
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003089 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003090 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003091 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003092 }
3093
3094 VISIT(c, expr, value);
3095 ADDOP(c, POP_TOP);
3096 return 1;
3097}
3098
3099static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003100compiler_visit_stmt(struct compiler *c, stmt_ty s)
3101{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003102 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 /* Always assign a lineno to the next instruction for a stmt. */
3105 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003106 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 switch (s->kind) {
3110 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003111 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 case ClassDef_kind:
3113 return compiler_class(c, s);
3114 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003115 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 case Delete_kind:
3117 VISIT_SEQ(c, expr, s->v.Delete.targets)
3118 break;
3119 case Assign_kind:
3120 n = asdl_seq_LEN(s->v.Assign.targets);
3121 VISIT(c, expr, s->v.Assign.value);
3122 for (i = 0; i < n; i++) {
3123 if (i < n - 1)
3124 ADDOP(c, DUP_TOP);
3125 VISIT(c, expr,
3126 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3127 }
3128 break;
3129 case AugAssign_kind:
3130 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003131 case AnnAssign_kind:
3132 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 case For_kind:
3134 return compiler_for(c, s);
3135 case While_kind:
3136 return compiler_while(c, s);
3137 case If_kind:
3138 return compiler_if(c, s);
3139 case Raise_kind:
3140 n = 0;
3141 if (s->v.Raise.exc) {
3142 VISIT(c, expr, s->v.Raise.exc);
3143 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003144 if (s->v.Raise.cause) {
3145 VISIT(c, expr, s->v.Raise.cause);
3146 n++;
3147 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003149 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003151 case Try_kind:
3152 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 case Assert_kind:
3154 return compiler_assert(c, s);
3155 case Import_kind:
3156 return compiler_import(c, s);
3157 case ImportFrom_kind:
3158 return compiler_from_import(c, s);
3159 case Global_kind:
3160 case Nonlocal_kind:
3161 break;
3162 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003163 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 case Pass_kind:
3165 break;
3166 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003167 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 case Continue_kind:
3169 return compiler_continue(c);
3170 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003171 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003172 case AsyncFunctionDef_kind:
3173 return compiler_function(c, s, 1);
3174 case AsyncWith_kind:
3175 return compiler_async_with(c, s, 0);
3176 case AsyncFor_kind:
3177 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 }
Yury Selivanov75445082015-05-11 22:57:16 -04003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
3184unaryop(unaryop_ty op)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 switch (op) {
3187 case Invert:
3188 return UNARY_INVERT;
3189 case Not:
3190 return UNARY_NOT;
3191 case UAdd:
3192 return UNARY_POSITIVE;
3193 case USub:
3194 return UNARY_NEGATIVE;
3195 default:
3196 PyErr_Format(PyExc_SystemError,
3197 "unary op %d should not be possible", op);
3198 return 0;
3199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200}
3201
3202static int
3203binop(struct compiler *c, operator_ty op)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 switch (op) {
3206 case Add:
3207 return BINARY_ADD;
3208 case Sub:
3209 return BINARY_SUBTRACT;
3210 case Mult:
3211 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003212 case MatMult:
3213 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 case Div:
3215 return BINARY_TRUE_DIVIDE;
3216 case Mod:
3217 return BINARY_MODULO;
3218 case Pow:
3219 return BINARY_POWER;
3220 case LShift:
3221 return BINARY_LSHIFT;
3222 case RShift:
3223 return BINARY_RSHIFT;
3224 case BitOr:
3225 return BINARY_OR;
3226 case BitXor:
3227 return BINARY_XOR;
3228 case BitAnd:
3229 return BINARY_AND;
3230 case FloorDiv:
3231 return BINARY_FLOOR_DIVIDE;
3232 default:
3233 PyErr_Format(PyExc_SystemError,
3234 "binary op %d should not be possible", op);
3235 return 0;
3236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237}
3238
3239static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240inplace_binop(struct compiler *c, operator_ty op)
3241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 switch (op) {
3243 case Add:
3244 return INPLACE_ADD;
3245 case Sub:
3246 return INPLACE_SUBTRACT;
3247 case Mult:
3248 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003249 case MatMult:
3250 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 case Div:
3252 return INPLACE_TRUE_DIVIDE;
3253 case Mod:
3254 return INPLACE_MODULO;
3255 case Pow:
3256 return INPLACE_POWER;
3257 case LShift:
3258 return INPLACE_LSHIFT;
3259 case RShift:
3260 return INPLACE_RSHIFT;
3261 case BitOr:
3262 return INPLACE_OR;
3263 case BitXor:
3264 return INPLACE_XOR;
3265 case BitAnd:
3266 return INPLACE_AND;
3267 case FloorDiv:
3268 return INPLACE_FLOOR_DIVIDE;
3269 default:
3270 PyErr_Format(PyExc_SystemError,
3271 "inplace binary op %d should not be possible", op);
3272 return 0;
3273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274}
3275
3276static int
3277compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3278{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003279 int op, scope;
3280 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 PyObject *dict = c->u->u_names;
3284 PyObject *mangled;
3285 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003287 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3288 !_PyUnicode_EqualToASCIIString(name, "True") &&
3289 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003290
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003291 mangled = _Py_Mangle(c->u->u_private, name);
3292 if (!mangled)
3293 return 0;
3294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 op = 0;
3296 optype = OP_NAME;
3297 scope = PyST_GetScope(c->u->u_ste, mangled);
3298 switch (scope) {
3299 case FREE:
3300 dict = c->u->u_freevars;
3301 optype = OP_DEREF;
3302 break;
3303 case CELL:
3304 dict = c->u->u_cellvars;
3305 optype = OP_DEREF;
3306 break;
3307 case LOCAL:
3308 if (c->u->u_ste->ste_type == FunctionBlock)
3309 optype = OP_FAST;
3310 break;
3311 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003312 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 optype = OP_GLOBAL;
3314 break;
3315 case GLOBAL_EXPLICIT:
3316 optype = OP_GLOBAL;
3317 break;
3318 default:
3319 /* scope can be 0 */
3320 break;
3321 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 switch (optype) {
3327 case OP_DEREF:
3328 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003329 case Load:
3330 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3331 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 case Store: op = STORE_DEREF; break;
3333 case AugLoad:
3334 case AugStore:
3335 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003336 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 case Param:
3338 default:
3339 PyErr_SetString(PyExc_SystemError,
3340 "param invalid for deref variable");
3341 return 0;
3342 }
3343 break;
3344 case OP_FAST:
3345 switch (ctx) {
3346 case Load: op = LOAD_FAST; break;
3347 case Store: op = STORE_FAST; break;
3348 case Del: op = DELETE_FAST; break;
3349 case AugLoad:
3350 case AugStore:
3351 break;
3352 case Param:
3353 default:
3354 PyErr_SetString(PyExc_SystemError,
3355 "param invalid for local variable");
3356 return 0;
3357 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003358 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 return 1;
3360 case OP_GLOBAL:
3361 switch (ctx) {
3362 case Load: op = LOAD_GLOBAL; break;
3363 case Store: op = STORE_GLOBAL; break;
3364 case Del: op = DELETE_GLOBAL; break;
3365 case AugLoad:
3366 case AugStore:
3367 break;
3368 case Param:
3369 default:
3370 PyErr_SetString(PyExc_SystemError,
3371 "param invalid for global variable");
3372 return 0;
3373 }
3374 break;
3375 case OP_NAME:
3376 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003377 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 case Store: op = STORE_NAME; break;
3379 case Del: op = DELETE_NAME; break;
3380 case AugLoad:
3381 case AugStore:
3382 break;
3383 case Param:
3384 default:
3385 PyErr_SetString(PyExc_SystemError,
3386 "param invalid for name variable");
3387 return 0;
3388 }
3389 break;
3390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 assert(op);
3393 arg = compiler_add_o(c, dict, mangled);
3394 Py_DECREF(mangled);
3395 if (arg < 0)
3396 return 0;
3397 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398}
3399
3400static int
3401compiler_boolop(struct compiler *c, expr_ty e)
3402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003404 int jumpi;
3405 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 assert(e->kind == BoolOp_kind);
3409 if (e->v.BoolOp.op == And)
3410 jumpi = JUMP_IF_FALSE_OR_POP;
3411 else
3412 jumpi = JUMP_IF_TRUE_OR_POP;
3413 end = compiler_new_block(c);
3414 if (end == NULL)
3415 return 0;
3416 s = e->v.BoolOp.values;
3417 n = asdl_seq_LEN(s) - 1;
3418 assert(n >= 0);
3419 for (i = 0; i < n; ++i) {
3420 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3421 ADDOP_JABS(c, jumpi, end);
3422 }
3423 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3424 compiler_use_next_block(c, end);
3425 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426}
3427
3428static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003429starunpack_helper(struct compiler *c, asdl_seq *elts,
3430 int single_op, int inner_op, int outer_op)
3431{
3432 Py_ssize_t n = asdl_seq_LEN(elts);
3433 Py_ssize_t i, nsubitems = 0, nseen = 0;
3434 for (i = 0; i < n; i++) {
3435 expr_ty elt = asdl_seq_GET(elts, i);
3436 if (elt->kind == Starred_kind) {
3437 if (nseen) {
3438 ADDOP_I(c, inner_op, nseen);
3439 nseen = 0;
3440 nsubitems++;
3441 }
3442 VISIT(c, expr, elt->v.Starred.value);
3443 nsubitems++;
3444 }
3445 else {
3446 VISIT(c, expr, elt);
3447 nseen++;
3448 }
3449 }
3450 if (nsubitems) {
3451 if (nseen) {
3452 ADDOP_I(c, inner_op, nseen);
3453 nsubitems++;
3454 }
3455 ADDOP_I(c, outer_op, nsubitems);
3456 }
3457 else
3458 ADDOP_I(c, single_op, nseen);
3459 return 1;
3460}
3461
3462static int
3463assignment_helper(struct compiler *c, asdl_seq *elts)
3464{
3465 Py_ssize_t n = asdl_seq_LEN(elts);
3466 Py_ssize_t i;
3467 int seen_star = 0;
3468 for (i = 0; i < n; i++) {
3469 expr_ty elt = asdl_seq_GET(elts, i);
3470 if (elt->kind == Starred_kind && !seen_star) {
3471 if ((i >= (1 << 8)) ||
3472 (n-i-1 >= (INT_MAX >> 8)))
3473 return compiler_error(c,
3474 "too many expressions in "
3475 "star-unpacking assignment");
3476 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3477 seen_star = 1;
3478 asdl_seq_SET(elts, i, elt->v.Starred.value);
3479 }
3480 else if (elt->kind == Starred_kind) {
3481 return compiler_error(c,
3482 "two starred expressions in assignment");
3483 }
3484 }
3485 if (!seen_star) {
3486 ADDOP_I(c, UNPACK_SEQUENCE, n);
3487 }
3488 VISIT_SEQ(c, expr, elts);
3489 return 1;
3490}
3491
3492static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493compiler_list(struct compiler *c, expr_ty e)
3494{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003495 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003497 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003499 else if (e->v.List.ctx == Load) {
3500 return starunpack_helper(c, elts,
3501 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003503 else
3504 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506}
3507
3508static int
3509compiler_tuple(struct compiler *c, expr_ty e)
3510{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003511 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513 return assignment_helper(c, elts);
3514 }
3515 else if (e->v.Tuple.ctx == Load) {
3516 return starunpack_helper(c, elts,
3517 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3518 }
3519 else
3520 VISIT_SEQ(c, expr, elts);
3521 return 1;
3522}
3523
3524static int
3525compiler_set(struct compiler *c, expr_ty e)
3526{
3527 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3528 BUILD_SET, BUILD_SET_UNPACK);
3529}
3530
3531static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003532are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3533{
3534 Py_ssize_t i;
3535 for (i = begin; i < end; i++) {
3536 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003537 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003538 return 0;
3539 }
3540 return 1;
3541}
3542
3543static int
3544compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3545{
3546 Py_ssize_t i, n = end - begin;
3547 PyObject *keys, *key;
3548 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3549 for (i = begin; i < end; i++) {
3550 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3551 }
3552 keys = PyTuple_New(n);
3553 if (keys == NULL) {
3554 return 0;
3555 }
3556 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003557 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003558 Py_INCREF(key);
3559 PyTuple_SET_ITEM(keys, i - begin, key);
3560 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003561 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003562 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3563 }
3564 else {
3565 for (i = begin; i < end; i++) {
3566 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3567 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3568 }
3569 ADDOP_I(c, BUILD_MAP, n);
3570 }
3571 return 1;
3572}
3573
3574static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003575compiler_dict(struct compiler *c, expr_ty e)
3576{
Victor Stinner976bb402016-03-23 11:36:19 +01003577 Py_ssize_t i, n, elements;
3578 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003579 int is_unpacking = 0;
3580 n = asdl_seq_LEN(e->v.Dict.values);
3581 containers = 0;
3582 elements = 0;
3583 for (i = 0; i < n; i++) {
3584 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3585 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003586 if (!compiler_subdict(c, e, i - elements, i))
3587 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003588 containers++;
3589 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003591 if (is_unpacking) {
3592 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3593 containers++;
3594 }
3595 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003596 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 }
3598 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003599 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003600 if (!compiler_subdict(c, e, n - elements, n))
3601 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003602 containers++;
3603 }
3604 /* If there is more than one dict, they need to be merged into a new
3605 * dict. If there is one dict and it's an unpacking, then it needs
3606 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003607 if (containers > 1 || is_unpacking) {
3608 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 }
3610 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611}
3612
3613static int
3614compiler_compare(struct compiler *c, expr_ty e)
3615{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003616 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003619 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3620 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3621 if (n == 0) {
3622 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3623 ADDOP_I(c, COMPARE_OP,
3624 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3625 }
3626 else {
3627 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 if (cleanup == NULL)
3629 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003630 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 VISIT(c, expr,
3632 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003633 ADDOP(c, DUP_TOP);
3634 ADDOP(c, ROT_THREE);
3635 ADDOP_I(c, COMPARE_OP,
3636 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3637 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3638 NEXT_BLOCK(c);
3639 }
3640 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3641 ADDOP_I(c, COMPARE_OP,
3642 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 basicblock *end = compiler_new_block(c);
3644 if (end == NULL)
3645 return 0;
3646 ADDOP_JREL(c, JUMP_FORWARD, end);
3647 compiler_use_next_block(c, cleanup);
3648 ADDOP(c, ROT_TWO);
3649 ADDOP(c, POP_TOP);
3650 compiler_use_next_block(c, end);
3651 }
3652 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653}
3654
3655static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003656maybe_optimize_method_call(struct compiler *c, expr_ty e)
3657{
3658 Py_ssize_t argsl, i;
3659 expr_ty meth = e->v.Call.func;
3660 asdl_seq *args = e->v.Call.args;
3661
3662 /* Check that the call node is an attribute access, and that
3663 the call doesn't have keyword parameters. */
3664 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3665 asdl_seq_LEN(e->v.Call.keywords))
3666 return -1;
3667
3668 /* Check that there are no *varargs types of arguments. */
3669 argsl = asdl_seq_LEN(args);
3670 for (i = 0; i < argsl; i++) {
3671 expr_ty elt = asdl_seq_GET(args, i);
3672 if (elt->kind == Starred_kind) {
3673 return -1;
3674 }
3675 }
3676
3677 /* Alright, we can optimize the code. */
3678 VISIT(c, expr, meth->v.Attribute.value);
3679 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3680 VISIT_SEQ(c, expr, e->v.Call.args);
3681 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3682 return 1;
3683}
3684
3685static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686compiler_call(struct compiler *c, expr_ty e)
3687{
Yury Selivanovf2392132016-12-13 19:03:51 -05003688 if (maybe_optimize_method_call(c, e) > 0)
3689 return 1;
3690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 VISIT(c, expr, e->v.Call.func);
3692 return compiler_call_helper(c, 0,
3693 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003694 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003695}
3696
Eric V. Smith235a6f02015-09-19 14:51:32 -04003697static int
3698compiler_joined_str(struct compiler *c, expr_ty e)
3699{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003700 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003701 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3702 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003703 return 1;
3704}
3705
Eric V. Smitha78c7952015-11-03 12:45:05 -05003706/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003707static int
3708compiler_formatted_value(struct compiler *c, expr_ty e)
3709{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003710 /* Our oparg encodes 2 pieces of information: the conversion
3711 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003712
Eric V. Smitha78c7952015-11-03 12:45:05 -05003713 Convert the conversion char to 2 bits:
3714 None: 000 0x0 FVC_NONE
3715 !s : 001 0x1 FVC_STR
3716 !r : 010 0x2 FVC_REPR
3717 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003718
Eric V. Smitha78c7952015-11-03 12:45:05 -05003719 next bit is whether or not we have a format spec:
3720 yes : 100 0x4
3721 no : 000 0x0
3722 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003723
Eric V. Smitha78c7952015-11-03 12:45:05 -05003724 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003725
Eric V. Smitha78c7952015-11-03 12:45:05 -05003726 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003727 VISIT(c, expr, e->v.FormattedValue.value);
3728
Eric V. Smitha78c7952015-11-03 12:45:05 -05003729 switch (e->v.FormattedValue.conversion) {
3730 case 's': oparg = FVC_STR; break;
3731 case 'r': oparg = FVC_REPR; break;
3732 case 'a': oparg = FVC_ASCII; break;
3733 case -1: oparg = FVC_NONE; break;
3734 default:
3735 PyErr_SetString(PyExc_SystemError,
3736 "Unrecognized conversion character");
3737 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003738 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003739 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003740 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003741 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003742 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003743 }
3744
Eric V. Smitha78c7952015-11-03 12:45:05 -05003745 /* And push our opcode and oparg */
3746 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003747 return 1;
3748}
3749
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003750static int
3751compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3752{
3753 Py_ssize_t i, n = end - begin;
3754 keyword_ty kw;
3755 PyObject *keys, *key;
3756 assert(n > 0);
3757 if (n > 1) {
3758 for (i = begin; i < end; i++) {
3759 kw = asdl_seq_GET(keywords, i);
3760 VISIT(c, expr, kw->value);
3761 }
3762 keys = PyTuple_New(n);
3763 if (keys == NULL) {
3764 return 0;
3765 }
3766 for (i = begin; i < end; i++) {
3767 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3768 Py_INCREF(key);
3769 PyTuple_SET_ITEM(keys, i - begin, key);
3770 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003771 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003772 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3773 }
3774 else {
3775 /* a for loop only executes once */
3776 for (i = begin; i < end; i++) {
3777 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003778 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003779 VISIT(c, expr, kw->value);
3780 }
3781 ADDOP_I(c, BUILD_MAP, n);
3782 }
3783 return 1;
3784}
3785
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003786/* shared code between compiler_call and compiler_class */
3787static int
3788compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003789 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003790 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003792{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003793 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003794 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003795
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 /* the number of tuples and dictionaries on the stack */
3797 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3798
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003800 nkwelts = asdl_seq_LEN(keywords);
3801
3802 for (i = 0; i < nkwelts; i++) {
3803 keyword_ty kw = asdl_seq_GET(keywords, i);
3804 if (kw->arg == NULL) {
3805 mustdictunpack = 1;
3806 break;
3807 }
3808 }
3809
3810 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811 for (i = 0; i < nelts; i++) {
3812 expr_ty elt = asdl_seq_GET(args, i);
3813 if (elt->kind == Starred_kind) {
3814 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003815 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003816 if (nseen) {
3817 ADDOP_I(c, BUILD_TUPLE, nseen);
3818 nseen = 0;
3819 nsubargs++;
3820 }
3821 VISIT(c, expr, elt->v.Starred.value);
3822 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003823 }
3824 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003825 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003826 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003829
3830 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003831 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003832 if (nseen) {
3833 /* Pack up any trailing positional arguments. */
3834 ADDOP_I(c, BUILD_TUPLE, nseen);
3835 nsubargs++;
3836 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003837 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003838 /* If we ended up with more than one stararg, we need
3839 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003840 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003841 }
3842 else if (nsubargs == 0) {
3843 ADDOP_I(c, BUILD_TUPLE, 0);
3844 }
3845 nseen = 0; /* the number of keyword arguments on the stack following */
3846 for (i = 0; i < nkwelts; i++) {
3847 keyword_ty kw = asdl_seq_GET(keywords, i);
3848 if (kw->arg == NULL) {
3849 /* A keyword argument unpacking. */
3850 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003851 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3852 return 0;
3853 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003854 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003855 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003856 VISIT(c, expr, kw->value);
3857 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003858 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003859 else {
3860 nseen++;
3861 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003862 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003863 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003864 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003865 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003866 return 0;
3867 nsubkwargs++;
3868 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003869 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003870 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003871 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003872 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003873 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3874 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003876 else if (nkwelts) {
3877 PyObject *names;
3878 VISIT_SEQ(c, keyword, keywords);
3879 names = PyTuple_New(nkwelts);
3880 if (names == NULL) {
3881 return 0;
3882 }
3883 for (i = 0; i < nkwelts; i++) {
3884 keyword_ty kw = asdl_seq_GET(keywords, i);
3885 Py_INCREF(kw->arg);
3886 PyTuple_SET_ITEM(names, i, kw->arg);
3887 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003888 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003889 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3890 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003892 else {
3893 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3894 return 1;
3895 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896}
3897
Nick Coghlan650f0d02007-04-15 12:05:43 +00003898
3899/* List and set comprehensions and generator expressions work by creating a
3900 nested function to perform the actual iteration. This means that the
3901 iteration variables don't leak into the current scope.
3902 The defined function is called immediately following its definition, with the
3903 result of that call being the result of the expression.
3904 The LC/SC version returns the populated container, while the GE version is
3905 flagged in symtable.c as a generator, so it returns the generator object
3906 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003907
3908 Possible cleanups:
3909 - iterate over the generator sequence instead of using recursion
3910*/
3911
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003912
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914compiler_comprehension_generator(struct compiler *c,
3915 asdl_seq *generators, int gen_index,
3916 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003918 comprehension_ty gen;
3919 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3920 if (gen->is_async) {
3921 return compiler_async_comprehension_generator(
3922 c, generators, gen_index, elt, val, type);
3923 } else {
3924 return compiler_sync_comprehension_generator(
3925 c, generators, gen_index, elt, val, type);
3926 }
3927}
3928
3929static int
3930compiler_sync_comprehension_generator(struct compiler *c,
3931 asdl_seq *generators, int gen_index,
3932 expr_ty elt, expr_ty val, int type)
3933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 /* generate code for the iterator, then each of the ifs,
3935 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 comprehension_ty gen;
3938 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003939 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 start = compiler_new_block(c);
3942 skip = compiler_new_block(c);
3943 if_cleanup = compiler_new_block(c);
3944 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3947 anchor == NULL)
3948 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 if (gen_index == 0) {
3953 /* Receive outermost iter as an implicit argument */
3954 c->u->u_argcount = 1;
3955 ADDOP_I(c, LOAD_FAST, 0);
3956 }
3957 else {
3958 /* Sub-iter - calculate on the fly */
3959 VISIT(c, expr, gen->iter);
3960 ADDOP(c, GET_ITER);
3961 }
3962 compiler_use_next_block(c, start);
3963 ADDOP_JREL(c, FOR_ITER, anchor);
3964 NEXT_BLOCK(c);
3965 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* XXX this needs to be cleaned up...a lot! */
3968 n = asdl_seq_LEN(gen->ifs);
3969 for (i = 0; i < n; i++) {
3970 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003971 if (!compiler_jump_if(c, e, if_cleanup, 0))
3972 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 NEXT_BLOCK(c);
3974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (++gen_index < asdl_seq_LEN(generators))
3977 if (!compiler_comprehension_generator(c,
3978 generators, gen_index,
3979 elt, val, type))
3980 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* only append after the last for generator */
3983 if (gen_index >= asdl_seq_LEN(generators)) {
3984 /* comprehension specific code */
3985 switch (type) {
3986 case COMP_GENEXP:
3987 VISIT(c, expr, elt);
3988 ADDOP(c, YIELD_VALUE);
3989 ADDOP(c, POP_TOP);
3990 break;
3991 case COMP_LISTCOMP:
3992 VISIT(c, expr, elt);
3993 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3994 break;
3995 case COMP_SETCOMP:
3996 VISIT(c, expr, elt);
3997 ADDOP_I(c, SET_ADD, gen_index + 1);
3998 break;
3999 case COMP_DICTCOMP:
4000 /* With 'd[k] = v', v is evaluated before k, so we do
4001 the same. */
4002 VISIT(c, expr, val);
4003 VISIT(c, expr, elt);
4004 ADDOP_I(c, MAP_ADD, gen_index + 1);
4005 break;
4006 default:
4007 return 0;
4008 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 compiler_use_next_block(c, skip);
4011 }
4012 compiler_use_next_block(c, if_cleanup);
4013 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4014 compiler_use_next_block(c, anchor);
4015
4016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017}
4018
4019static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004020compiler_async_comprehension_generator(struct compiler *c,
4021 asdl_seq *generators, int gen_index,
4022 expr_ty elt, expr_ty val, int type)
4023{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004024 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004025 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004026 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004027 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004028 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004029 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004030
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004031 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004032 return 0;
4033 }
4034
4035 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4036
4037 if (gen_index == 0) {
4038 /* Receive outermost iter as an implicit argument */
4039 c->u->u_argcount = 1;
4040 ADDOP_I(c, LOAD_FAST, 0);
4041 }
4042 else {
4043 /* Sub-iter - calculate on the fly */
4044 VISIT(c, expr, gen->iter);
4045 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004046 }
4047
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004048 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004049
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004050 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004051 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004052 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004053 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004055 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004056
4057 n = asdl_seq_LEN(gen->ifs);
4058 for (i = 0; i < n; i++) {
4059 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004060 if (!compiler_jump_if(c, e, if_cleanup, 0))
4061 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004062 NEXT_BLOCK(c);
4063 }
4064
4065 if (++gen_index < asdl_seq_LEN(generators))
4066 if (!compiler_comprehension_generator(c,
4067 generators, gen_index,
4068 elt, val, type))
4069 return 0;
4070
4071 /* only append after the last for generator */
4072 if (gen_index >= asdl_seq_LEN(generators)) {
4073 /* comprehension specific code */
4074 switch (type) {
4075 case COMP_GENEXP:
4076 VISIT(c, expr, elt);
4077 ADDOP(c, YIELD_VALUE);
4078 ADDOP(c, POP_TOP);
4079 break;
4080 case COMP_LISTCOMP:
4081 VISIT(c, expr, elt);
4082 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4083 break;
4084 case COMP_SETCOMP:
4085 VISIT(c, expr, elt);
4086 ADDOP_I(c, SET_ADD, gen_index + 1);
4087 break;
4088 case COMP_DICTCOMP:
4089 /* With 'd[k] = v', v is evaluated before k, so we do
4090 the same. */
4091 VISIT(c, expr, val);
4092 VISIT(c, expr, elt);
4093 ADDOP_I(c, MAP_ADD, gen_index + 1);
4094 break;
4095 default:
4096 return 0;
4097 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004098 }
4099 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004100 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4101
4102 compiler_use_next_block(c, except);
4103 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004104
4105 return 1;
4106}
4107
4108static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004109compiler_comprehension(struct compiler *c, expr_ty e, int type,
4110 identifier name, asdl_seq *generators, expr_ty elt,
4111 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004114 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004115 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004116 int is_async_function = c->u->u_ste->ste_coroutine;
4117 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004118
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004119 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004120
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004121 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4122 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004123 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004125 }
4126
4127 is_async_generator = c->u->u_ste->ste_coroutine;
4128
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004129 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004130 compiler_error(c, "asynchronous comprehension outside of "
4131 "an asynchronous function");
4132 goto error_in_scope;
4133 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 if (type != COMP_GENEXP) {
4136 int op;
4137 switch (type) {
4138 case COMP_LISTCOMP:
4139 op = BUILD_LIST;
4140 break;
4141 case COMP_SETCOMP:
4142 op = BUILD_SET;
4143 break;
4144 case COMP_DICTCOMP:
4145 op = BUILD_MAP;
4146 break;
4147 default:
4148 PyErr_Format(PyExc_SystemError,
4149 "unknown comprehension type %d", type);
4150 goto error_in_scope;
4151 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 ADDOP_I(c, op, 0);
4154 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 if (!compiler_comprehension_generator(c, generators, 0, elt,
4157 val, type))
4158 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 if (type != COMP_GENEXP) {
4161 ADDOP(c, RETURN_VALUE);
4162 }
4163
4164 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004165 qualname = c->u->u_qualname;
4166 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004168 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 goto error;
4170
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004171 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004173 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 Py_DECREF(co);
4175
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004176 VISIT(c, expr, outermost->iter);
4177
4178 if (outermost->is_async) {
4179 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004180 } else {
4181 ADDOP(c, GET_ITER);
4182 }
4183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004185
4186 if (is_async_generator && type != COMP_GENEXP) {
4187 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004188 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004189 ADDOP(c, YIELD_FROM);
4190 }
4191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004193error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004195error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004196 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 Py_XDECREF(co);
4198 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004199}
4200
4201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004202compiler_genexp(struct compiler *c, expr_ty e)
4203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 static identifier name;
4205 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004206 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 if (!name)
4208 return 0;
4209 }
4210 assert(e->kind == GeneratorExp_kind);
4211 return compiler_comprehension(c, e, COMP_GENEXP, name,
4212 e->v.GeneratorExp.generators,
4213 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004214}
4215
4216static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004217compiler_listcomp(struct compiler *c, expr_ty e)
4218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 static identifier name;
4220 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004221 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (!name)
4223 return 0;
4224 }
4225 assert(e->kind == ListComp_kind);
4226 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4227 e->v.ListComp.generators,
4228 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004229}
4230
4231static int
4232compiler_setcomp(struct compiler *c, expr_ty e)
4233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 static identifier name;
4235 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004236 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 if (!name)
4238 return 0;
4239 }
4240 assert(e->kind == SetComp_kind);
4241 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4242 e->v.SetComp.generators,
4243 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004244}
4245
4246
4247static int
4248compiler_dictcomp(struct compiler *c, expr_ty e)
4249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 static identifier name;
4251 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004252 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 if (!name)
4254 return 0;
4255 }
4256 assert(e->kind == DictComp_kind);
4257 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4258 e->v.DictComp.generators,
4259 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004260}
4261
4262
4263static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264compiler_visit_keyword(struct compiler *c, keyword_ty k)
4265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 VISIT(c, expr, k->value);
4267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268}
4269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004271 whether they are true or false.
4272
4273 Return values: 1 for true, 0 for false, -1 for non-constant.
4274 */
4275
4276static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004277expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004279 if (e->kind == Constant_kind) {
4280 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004281 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004282 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283}
4284
Yury Selivanov75445082015-05-11 22:57:16 -04004285
4286/*
4287 Implements the async with statement.
4288
4289 The semantics outlined in that PEP are as follows:
4290
4291 async with EXPR as VAR:
4292 BLOCK
4293
4294 It is implemented roughly as:
4295
4296 context = EXPR
4297 exit = context.__aexit__ # not calling it
4298 value = await context.__aenter__()
4299 try:
4300 VAR = value # if VAR present in the syntax
4301 BLOCK
4302 finally:
4303 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004304 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004305 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004306 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004307 if not (await exit(*exc)):
4308 raise
4309 */
4310static int
4311compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4312{
4313 basicblock *block, *finally;
4314 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4315
4316 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004317 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4318 return compiler_error(c, "'async with' outside async function");
4319 }
Yury Selivanov75445082015-05-11 22:57:16 -04004320
4321 block = compiler_new_block(c);
4322 finally = compiler_new_block(c);
4323 if (!block || !finally)
4324 return 0;
4325
4326 /* Evaluate EXPR */
4327 VISIT(c, expr, item->context_expr);
4328
4329 ADDOP(c, BEFORE_ASYNC_WITH);
4330 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004331 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004332 ADDOP(c, YIELD_FROM);
4333
4334 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4335
4336 /* SETUP_ASYNC_WITH pushes a finally block. */
4337 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004338 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004339 return 0;
4340 }
4341
4342 if (item->optional_vars) {
4343 VISIT(c, expr, item->optional_vars);
4344 }
4345 else {
4346 /* Discard result from context.__aenter__() */
4347 ADDOP(c, POP_TOP);
4348 }
4349
4350 pos++;
4351 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4352 /* BLOCK code */
4353 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4354 else if (!compiler_async_with(c, s, pos))
4355 return 0;
4356
4357 /* End of try block; start the finally block */
4358 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004359 ADDOP(c, BEGIN_FINALLY);
4360 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004361
Yury Selivanov75445082015-05-11 22:57:16 -04004362 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004363 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004364 return 0;
4365
4366 /* Finally block starts; context.__exit__ is on the stack under
4367 the exception or return information. Just issue our magic
4368 opcode. */
4369 ADDOP(c, WITH_CLEANUP_START);
4370
4371 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004372 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004373 ADDOP(c, YIELD_FROM);
4374
4375 ADDOP(c, WITH_CLEANUP_FINISH);
4376
4377 /* Finally block ends. */
4378 ADDOP(c, END_FINALLY);
4379 compiler_pop_fblock(c, FINALLY_END, finally);
4380 return 1;
4381}
4382
4383
Guido van Rossumc2e20742006-02-27 22:32:47 +00004384/*
4385 Implements the with statement from PEP 343.
4386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004388
4389 with EXPR as VAR:
4390 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391
Guido van Rossumc2e20742006-02-27 22:32:47 +00004392 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393
Thomas Wouters477c8d52006-05-27 19:21:47 +00004394 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004395 exit = context.__exit__ # not calling it
4396 value = context.__enter__()
4397 try:
4398 VAR = value # if VAR present in the syntax
4399 BLOCK
4400 finally:
4401 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004402 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004403 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004404 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004405 exit(*exc)
4406 */
4407static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004408compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004409{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004410 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004411 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004412
4413 assert(s->kind == With_kind);
4414
Guido van Rossumc2e20742006-02-27 22:32:47 +00004415 block = compiler_new_block(c);
4416 finally = compiler_new_block(c);
4417 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004418 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004419
Thomas Wouters477c8d52006-05-27 19:21:47 +00004420 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004421 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004422 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004423
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004424 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004425 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004426 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004427 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004428 }
4429
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004430 if (item->optional_vars) {
4431 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004432 }
4433 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004435 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004436 }
4437
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004438 pos++;
4439 if (pos == asdl_seq_LEN(s->v.With.items))
4440 /* BLOCK code */
4441 VISIT_SEQ(c, stmt, s->v.With.body)
4442 else if (!compiler_with(c, s, pos))
4443 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004444
4445 /* End of try block; start the finally block */
4446 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004447 ADDOP(c, BEGIN_FINALLY);
4448 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004449
Guido van Rossumc2e20742006-02-27 22:32:47 +00004450 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004451 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004452 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004453
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004454 /* Finally block starts; context.__exit__ is on the stack under
4455 the exception or return information. Just issue our magic
4456 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004457 ADDOP(c, WITH_CLEANUP_START);
4458 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004459
4460 /* Finally block ends. */
4461 ADDOP(c, END_FINALLY);
4462 compiler_pop_fblock(c, FINALLY_END, finally);
4463 return 1;
4464}
4465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004466static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004467compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 switch (e->kind) {
4470 case BoolOp_kind:
4471 return compiler_boolop(c, e);
4472 case BinOp_kind:
4473 VISIT(c, expr, e->v.BinOp.left);
4474 VISIT(c, expr, e->v.BinOp.right);
4475 ADDOP(c, binop(c, e->v.BinOp.op));
4476 break;
4477 case UnaryOp_kind:
4478 VISIT(c, expr, e->v.UnaryOp.operand);
4479 ADDOP(c, unaryop(e->v.UnaryOp.op));
4480 break;
4481 case Lambda_kind:
4482 return compiler_lambda(c, e);
4483 case IfExp_kind:
4484 return compiler_ifexp(c, e);
4485 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004486 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004488 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 case GeneratorExp_kind:
4490 return compiler_genexp(c, e);
4491 case ListComp_kind:
4492 return compiler_listcomp(c, e);
4493 case SetComp_kind:
4494 return compiler_setcomp(c, e);
4495 case DictComp_kind:
4496 return compiler_dictcomp(c, e);
4497 case Yield_kind:
4498 if (c->u->u_ste->ste_type != FunctionBlock)
4499 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004500 if (e->v.Yield.value) {
4501 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 }
4503 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004504 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004506 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004508 case YieldFrom_kind:
4509 if (c->u->u_ste->ste_type != FunctionBlock)
4510 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004511
4512 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4513 return compiler_error(c, "'yield from' inside async function");
4514
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004515 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004516 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004517 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004518 ADDOP(c, YIELD_FROM);
4519 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004520 case Await_kind:
4521 if (c->u->u_ste->ste_type != FunctionBlock)
4522 return compiler_error(c, "'await' outside function");
4523
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4525 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004526 return compiler_error(c, "'await' outside async function");
4527
4528 VISIT(c, expr, e->v.Await.value);
4529 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004530 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004531 ADDOP(c, YIELD_FROM);
4532 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 case Compare_kind:
4534 return compiler_compare(c, e);
4535 case Call_kind:
4536 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004537 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004538 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004539 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004540 case JoinedStr_kind:
4541 return compiler_joined_str(c, e);
4542 case FormattedValue_kind:
4543 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 /* The following exprs can be assignment targets. */
4545 case Attribute_kind:
4546 if (e->v.Attribute.ctx != AugStore)
4547 VISIT(c, expr, e->v.Attribute.value);
4548 switch (e->v.Attribute.ctx) {
4549 case AugLoad:
4550 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004551 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 case Load:
4553 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4554 break;
4555 case AugStore:
4556 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004557 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 case Store:
4559 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4560 break;
4561 case Del:
4562 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4563 break;
4564 case Param:
4565 default:
4566 PyErr_SetString(PyExc_SystemError,
4567 "param invalid in attribute expression");
4568 return 0;
4569 }
4570 break;
4571 case Subscript_kind:
4572 switch (e->v.Subscript.ctx) {
4573 case AugLoad:
4574 VISIT(c, expr, e->v.Subscript.value);
4575 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4576 break;
4577 case Load:
4578 VISIT(c, expr, e->v.Subscript.value);
4579 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4580 break;
4581 case AugStore:
4582 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4583 break;
4584 case Store:
4585 VISIT(c, expr, e->v.Subscript.value);
4586 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4587 break;
4588 case Del:
4589 VISIT(c, expr, e->v.Subscript.value);
4590 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4591 break;
4592 case Param:
4593 default:
4594 PyErr_SetString(PyExc_SystemError,
4595 "param invalid in subscript expression");
4596 return 0;
4597 }
4598 break;
4599 case Starred_kind:
4600 switch (e->v.Starred.ctx) {
4601 case Store:
4602 /* In all legitimate cases, the Starred node was already replaced
4603 * by compiler_list/compiler_tuple. XXX: is that okay? */
4604 return compiler_error(c,
4605 "starred assignment target must be in a list or tuple");
4606 default:
4607 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004608 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 }
4610 break;
4611 case Name_kind:
4612 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4613 /* child nodes of List and Tuple will have expr_context set */
4614 case List_kind:
4615 return compiler_list(c, e);
4616 case Tuple_kind:
4617 return compiler_tuple(c, e);
4618 }
4619 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004620}
4621
4622static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004623compiler_visit_expr(struct compiler *c, expr_ty e)
4624{
4625 /* If expr e has a different line number than the last expr/stmt,
4626 set a new line number for the next instruction.
4627 */
4628 int old_lineno = c->u->u_lineno;
4629 int old_col_offset = c->u->u_col_offset;
4630 if (e->lineno != c->u->u_lineno) {
4631 c->u->u_lineno = e->lineno;
4632 c->u->u_lineno_set = 0;
4633 }
4634 /* Updating the column offset is always harmless. */
4635 c->u->u_col_offset = e->col_offset;
4636
4637 int res = compiler_visit_expr1(c, e);
4638
4639 if (old_lineno != c->u->u_lineno) {
4640 c->u->u_lineno = old_lineno;
4641 c->u->u_lineno_set = 0;
4642 }
4643 c->u->u_col_offset = old_col_offset;
4644 return res;
4645}
4646
4647static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004648compiler_augassign(struct compiler *c, stmt_ty s)
4649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 expr_ty e = s->v.AugAssign.target;
4651 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 switch (e->kind) {
4656 case Attribute_kind:
4657 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4658 AugLoad, e->lineno, e->col_offset, c->c_arena);
4659 if (auge == NULL)
4660 return 0;
4661 VISIT(c, expr, auge);
4662 VISIT(c, expr, s->v.AugAssign.value);
4663 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4664 auge->v.Attribute.ctx = AugStore;
4665 VISIT(c, expr, auge);
4666 break;
4667 case Subscript_kind:
4668 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4669 AugLoad, e->lineno, e->col_offset, c->c_arena);
4670 if (auge == NULL)
4671 return 0;
4672 VISIT(c, expr, auge);
4673 VISIT(c, expr, s->v.AugAssign.value);
4674 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4675 auge->v.Subscript.ctx = AugStore;
4676 VISIT(c, expr, auge);
4677 break;
4678 case Name_kind:
4679 if (!compiler_nameop(c, e->v.Name.id, Load))
4680 return 0;
4681 VISIT(c, expr, s->v.AugAssign.value);
4682 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4683 return compiler_nameop(c, e->v.Name.id, Store);
4684 default:
4685 PyErr_Format(PyExc_SystemError,
4686 "invalid node type (%d) for augmented assignment",
4687 e->kind);
4688 return 0;
4689 }
4690 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691}
4692
4693static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004694check_ann_expr(struct compiler *c, expr_ty e)
4695{
4696 VISIT(c, expr, e);
4697 ADDOP(c, POP_TOP);
4698 return 1;
4699}
4700
4701static int
4702check_annotation(struct compiler *c, stmt_ty s)
4703{
4704 /* Annotations are only evaluated in a module or class. */
4705 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4706 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4707 return check_ann_expr(c, s->v.AnnAssign.annotation);
4708 }
4709 return 1;
4710}
4711
4712static int
4713check_ann_slice(struct compiler *c, slice_ty sl)
4714{
4715 switch(sl->kind) {
4716 case Index_kind:
4717 return check_ann_expr(c, sl->v.Index.value);
4718 case Slice_kind:
4719 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4720 return 0;
4721 }
4722 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4723 return 0;
4724 }
4725 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4726 return 0;
4727 }
4728 break;
4729 default:
4730 PyErr_SetString(PyExc_SystemError,
4731 "unexpected slice kind");
4732 return 0;
4733 }
4734 return 1;
4735}
4736
4737static int
4738check_ann_subscr(struct compiler *c, slice_ty sl)
4739{
4740 /* We check that everything in a subscript is defined at runtime. */
4741 Py_ssize_t i, n;
4742
4743 switch (sl->kind) {
4744 case Index_kind:
4745 case Slice_kind:
4746 if (!check_ann_slice(c, sl)) {
4747 return 0;
4748 }
4749 break;
4750 case ExtSlice_kind:
4751 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4752 for (i = 0; i < n; i++) {
4753 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4754 switch (subsl->kind) {
4755 case Index_kind:
4756 case Slice_kind:
4757 if (!check_ann_slice(c, subsl)) {
4758 return 0;
4759 }
4760 break;
4761 case ExtSlice_kind:
4762 default:
4763 PyErr_SetString(PyExc_SystemError,
4764 "extended slice invalid in nested slice");
4765 return 0;
4766 }
4767 }
4768 break;
4769 default:
4770 PyErr_Format(PyExc_SystemError,
4771 "invalid subscript kind %d", sl->kind);
4772 return 0;
4773 }
4774 return 1;
4775}
4776
4777static int
4778compiler_annassign(struct compiler *c, stmt_ty s)
4779{
4780 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004781 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004782
4783 assert(s->kind == AnnAssign_kind);
4784
4785 /* We perform the actual assignment first. */
4786 if (s->v.AnnAssign.value) {
4787 VISIT(c, expr, s->v.AnnAssign.value);
4788 VISIT(c, expr, targ);
4789 }
4790 switch (targ->kind) {
4791 case Name_kind:
4792 /* If we have a simple name in a module or class, store annotation. */
4793 if (s->v.AnnAssign.simple &&
4794 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4795 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004796 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4797 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4798 }
4799 else {
4800 VISIT(c, expr, s->v.AnnAssign.annotation);
4801 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004802 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004803 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004804 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004805 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004806 }
4807 break;
4808 case Attribute_kind:
4809 if (!s->v.AnnAssign.value &&
4810 !check_ann_expr(c, targ->v.Attribute.value)) {
4811 return 0;
4812 }
4813 break;
4814 case Subscript_kind:
4815 if (!s->v.AnnAssign.value &&
4816 (!check_ann_expr(c, targ->v.Subscript.value) ||
4817 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4818 return 0;
4819 }
4820 break;
4821 default:
4822 PyErr_Format(PyExc_SystemError,
4823 "invalid node type (%d) for annotated assignment",
4824 targ->kind);
4825 return 0;
4826 }
4827 /* Annotation is evaluated last. */
4828 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4829 return 0;
4830 }
4831 return 1;
4832}
4833
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004834/* Raises a SyntaxError and returns 0.
4835 If something goes wrong, a different exception may be raised.
4836*/
4837
4838static int
4839compiler_error(struct compiler *c, const char *errstr)
4840{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004841 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843
Victor Stinner14e461d2013-08-26 22:28:21 +02004844 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 if (!loc) {
4846 Py_INCREF(Py_None);
4847 loc = Py_None;
4848 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004849 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004850 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 if (!u)
4852 goto exit;
4853 v = Py_BuildValue("(zO)", errstr, u);
4854 if (!v)
4855 goto exit;
4856 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004857 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 Py_DECREF(loc);
4859 Py_XDECREF(u);
4860 Py_XDECREF(v);
4861 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004862}
4863
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004864/* Emits a SyntaxWarning and returns 1 on success.
4865 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4866 and returns 0.
4867*/
4868static int
4869compiler_warn(struct compiler *c, const char *errstr)
4870{
4871 PyObject *msg = PyUnicode_FromString(errstr);
4872 if (msg == NULL) {
4873 return 0;
4874 }
4875 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4876 c->u->u_lineno, NULL, NULL) < 0)
4877 {
4878 Py_DECREF(msg);
4879 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4880 PyErr_Clear();
4881 return compiler_error(c, errstr);
4882 }
4883 return 0;
4884 }
4885 Py_DECREF(msg);
4886 return 1;
4887}
4888
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004889static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890compiler_handle_subscr(struct compiler *c, const char *kind,
4891 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 /* XXX this code is duplicated */
4896 switch (ctx) {
4897 case AugLoad: /* fall through to Load */
4898 case Load: op = BINARY_SUBSCR; break;
4899 case AugStore:/* fall through to Store */
4900 case Store: op = STORE_SUBSCR; break;
4901 case Del: op = DELETE_SUBSCR; break;
4902 case Param:
4903 PyErr_Format(PyExc_SystemError,
4904 "invalid %s kind %d in subscript\n",
4905 kind, ctx);
4906 return 0;
4907 }
4908 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004909 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 }
4911 else if (ctx == AugStore) {
4912 ADDOP(c, ROT_THREE);
4913 }
4914 ADDOP(c, op);
4915 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004916}
4917
4918static int
4919compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 int n = 2;
4922 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 /* only handles the cases where BUILD_SLICE is emitted */
4925 if (s->v.Slice.lower) {
4926 VISIT(c, expr, s->v.Slice.lower);
4927 }
4928 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004929 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 if (s->v.Slice.upper) {
4933 VISIT(c, expr, s->v.Slice.upper);
4934 }
4935 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004936 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004937 }
4938
4939 if (s->v.Slice.step) {
4940 n++;
4941 VISIT(c, expr, s->v.Slice.step);
4942 }
4943 ADDOP_I(c, BUILD_SLICE, n);
4944 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004945}
4946
4947static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4949 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 switch (s->kind) {
4952 case Slice_kind:
4953 return compiler_slice(c, s, ctx);
4954 case Index_kind:
4955 VISIT(c, expr, s->v.Index.value);
4956 break;
4957 case ExtSlice_kind:
4958 default:
4959 PyErr_SetString(PyExc_SystemError,
4960 "extended slice invalid in nested slice");
4961 return 0;
4962 }
4963 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964}
4965
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966static int
4967compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4968{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004969 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 switch (s->kind) {
4971 case Index_kind:
4972 kindname = "index";
4973 if (ctx != AugStore) {
4974 VISIT(c, expr, s->v.Index.value);
4975 }
4976 break;
4977 case Slice_kind:
4978 kindname = "slice";
4979 if (ctx != AugStore) {
4980 if (!compiler_slice(c, s, ctx))
4981 return 0;
4982 }
4983 break;
4984 case ExtSlice_kind:
4985 kindname = "extended slice";
4986 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004987 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 for (i = 0; i < n; i++) {
4989 slice_ty sub = (slice_ty)asdl_seq_GET(
4990 s->v.ExtSlice.dims, i);
4991 if (!compiler_visit_nested_slice(c, sub, ctx))
4992 return 0;
4993 }
4994 ADDOP_I(c, BUILD_TUPLE, n);
4995 }
4996 break;
4997 default:
4998 PyErr_Format(PyExc_SystemError,
4999 "invalid subscript kind %d", s->kind);
5000 return 0;
5001 }
5002 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005003}
5004
Thomas Wouters89f507f2006-12-13 04:49:30 +00005005/* End of the compiler section, beginning of the assembler section */
5006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005007/* do depth-first search of basic block graph, starting with block.
5008 post records the block indices in post-order.
5009
5010 XXX must handle implicit jumps from one block to next
5011*/
5012
Thomas Wouters89f507f2006-12-13 04:49:30 +00005013struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 PyObject *a_bytecode; /* string containing bytecode */
5015 int a_offset; /* offset into bytecode */
5016 int a_nblocks; /* number of reachable blocks */
5017 basicblock **a_postorder; /* list of blocks in dfs postorder */
5018 PyObject *a_lnotab; /* string containing lnotab */
5019 int a_lnotab_off; /* offset into lnotab */
5020 int a_lineno; /* last lineno of emitted instruction */
5021 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005022};
5023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005024static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005025dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005026{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005027 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005028
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005029 /* Get rid of recursion for normal control flow.
5030 Since the number of blocks is limited, unused space in a_postorder
5031 (from a_nblocks to end) can be used as a stack for still not ordered
5032 blocks. */
5033 for (j = end; b && !b->b_seen; b = b->b_next) {
5034 b->b_seen = 1;
5035 assert(a->a_nblocks < j);
5036 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005038 while (j < end) {
5039 b = a->a_postorder[j++];
5040 for (i = 0; i < b->b_iused; i++) {
5041 struct instr *instr = &b->b_instr[i];
5042 if (instr->i_jrel || instr->i_jabs)
5043 dfs(c, instr->i_target, a, j);
5044 }
5045 assert(a->a_nblocks < j);
5046 a->a_postorder[a->a_nblocks++] = b;
5047 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005048}
5049
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005050Py_LOCAL_INLINE(void)
5051stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005052{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005053 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005054 if (b->b_startdepth < depth) {
5055 assert(b->b_startdepth < 0);
5056 b->b_startdepth = depth;
5057 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005059}
5060
5061/* Find the flow path that needs the largest stack. We assume that
5062 * cycles in the flow graph have no net effect on the stack depth.
5063 */
5064static int
5065stackdepth(struct compiler *c)
5066{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005067 basicblock *b, *entryblock = NULL;
5068 basicblock **stack, **sp;
5069 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 b->b_startdepth = INT_MIN;
5072 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005073 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 }
5075 if (!entryblock)
5076 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005077 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5078 if (!stack) {
5079 PyErr_NoMemory();
5080 return -1;
5081 }
5082
5083 sp = stack;
5084 stackdepth_push(&sp, entryblock, 0);
5085 while (sp != stack) {
5086 b = *--sp;
5087 int depth = b->b_startdepth;
5088 assert(depth >= 0);
5089 basicblock *next = b->b_next;
5090 for (int i = 0; i < b->b_iused; i++) {
5091 struct instr *instr = &b->b_instr[i];
5092 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5093 if (effect == PY_INVALID_STACK_EFFECT) {
5094 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5095 Py_FatalError("PyCompile_OpcodeStackEffect()");
5096 }
5097 int new_depth = depth + effect;
5098 if (new_depth > maxdepth) {
5099 maxdepth = new_depth;
5100 }
5101 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5102 if (instr->i_jrel || instr->i_jabs) {
5103 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5104 assert(effect != PY_INVALID_STACK_EFFECT);
5105 int target_depth = depth + effect;
5106 if (target_depth > maxdepth) {
5107 maxdepth = target_depth;
5108 }
5109 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005110 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005111 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005112 assert(instr->i_target->b_startdepth >= target_depth);
5113 depth = new_depth;
5114 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005115 }
5116 stackdepth_push(&sp, instr->i_target, target_depth);
5117 }
5118 depth = new_depth;
5119 if (instr->i_opcode == JUMP_ABSOLUTE ||
5120 instr->i_opcode == JUMP_FORWARD ||
5121 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005122 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005123 {
5124 /* remaining code is dead */
5125 next = NULL;
5126 break;
5127 }
5128 }
5129 if (next != NULL) {
5130 stackdepth_push(&sp, next, depth);
5131 }
5132 }
5133 PyObject_Free(stack);
5134 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005135}
5136
5137static int
5138assemble_init(struct assembler *a, int nblocks, int firstlineno)
5139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 memset(a, 0, sizeof(struct assembler));
5141 a->a_lineno = firstlineno;
5142 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5143 if (!a->a_bytecode)
5144 return 0;
5145 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5146 if (!a->a_lnotab)
5147 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005148 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 PyErr_NoMemory();
5150 return 0;
5151 }
5152 a->a_postorder = (basicblock **)PyObject_Malloc(
5153 sizeof(basicblock *) * nblocks);
5154 if (!a->a_postorder) {
5155 PyErr_NoMemory();
5156 return 0;
5157 }
5158 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005159}
5160
5161static void
5162assemble_free(struct assembler *a)
5163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 Py_XDECREF(a->a_bytecode);
5165 Py_XDECREF(a->a_lnotab);
5166 if (a->a_postorder)
5167 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005168}
5169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005170static int
5171blocksize(basicblock *b)
5172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 int i;
5174 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005177 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005179}
5180
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005181/* Appends a pair to the end of the line number table, a_lnotab, representing
5182 the instruction's bytecode offset and line number. See
5183 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005184
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005185static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005186assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005189 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005191
Serhiy Storchakaab874002016-09-11 13:48:15 +03005192 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 if(d_bytecode == 0 && d_lineno == 0)
5198 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 if (d_bytecode > 255) {
5201 int j, nbytes, ncodes = d_bytecode / 255;
5202 nbytes = a->a_lnotab_off + 2 * ncodes;
5203 len = PyBytes_GET_SIZE(a->a_lnotab);
5204 if (nbytes >= len) {
5205 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5206 len = nbytes;
5207 else if (len <= INT_MAX / 2)
5208 len *= 2;
5209 else {
5210 PyErr_NoMemory();
5211 return 0;
5212 }
5213 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5214 return 0;
5215 }
5216 lnotab = (unsigned char *)
5217 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5218 for (j = 0; j < ncodes; j++) {
5219 *lnotab++ = 255;
5220 *lnotab++ = 0;
5221 }
5222 d_bytecode -= ncodes * 255;
5223 a->a_lnotab_off += ncodes * 2;
5224 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005225 assert(0 <= d_bytecode && d_bytecode <= 255);
5226
5227 if (d_lineno < -128 || 127 < d_lineno) {
5228 int j, nbytes, ncodes, k;
5229 if (d_lineno < 0) {
5230 k = -128;
5231 /* use division on positive numbers */
5232 ncodes = (-d_lineno) / 128;
5233 }
5234 else {
5235 k = 127;
5236 ncodes = d_lineno / 127;
5237 }
5238 d_lineno -= ncodes * k;
5239 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 nbytes = a->a_lnotab_off + 2 * ncodes;
5241 len = PyBytes_GET_SIZE(a->a_lnotab);
5242 if (nbytes >= len) {
5243 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5244 len = nbytes;
5245 else if (len <= INT_MAX / 2)
5246 len *= 2;
5247 else {
5248 PyErr_NoMemory();
5249 return 0;
5250 }
5251 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5252 return 0;
5253 }
5254 lnotab = (unsigned char *)
5255 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5256 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005257 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 d_bytecode = 0;
5259 for (j = 1; j < ncodes; j++) {
5260 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005261 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 a->a_lnotab_off += ncodes * 2;
5264 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005265 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 len = PyBytes_GET_SIZE(a->a_lnotab);
5268 if (a->a_lnotab_off + 2 >= len) {
5269 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5270 return 0;
5271 }
5272 lnotab = (unsigned char *)
5273 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 a->a_lnotab_off += 2;
5276 if (d_bytecode) {
5277 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005278 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 }
5280 else { /* First line of a block; def stmt, etc. */
5281 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005282 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 }
5284 a->a_lineno = i->i_lineno;
5285 a->a_lineno_off = a->a_offset;
5286 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005287}
5288
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005289/* assemble_emit()
5290 Extend the bytecode with a new instruction.
5291 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005292*/
5293
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005294static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005296{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005297 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005299 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005300
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005301 arg = i->i_oparg;
5302 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 if (i->i_lineno && !assemble_lnotab(a, i))
5304 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005305 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 if (len > PY_SSIZE_T_MAX / 2)
5307 return 0;
5308 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5309 return 0;
5310 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005311 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005313 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005315}
5316
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005317static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005321 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 /* Compute the size of each block and fixup jump args.
5325 Replace block pointer with position in bytecode. */
5326 do {
5327 totsize = 0;
5328 for (i = a->a_nblocks - 1; i >= 0; i--) {
5329 b = a->a_postorder[i];
5330 bsize = blocksize(b);
5331 b->b_offset = totsize;
5332 totsize += bsize;
5333 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005334 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5336 bsize = b->b_offset;
5337 for (i = 0; i < b->b_iused; i++) {
5338 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005339 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 /* Relative jumps are computed relative to
5341 the instruction pointer after fetching
5342 the jump instruction.
5343 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005344 bsize += isize;
5345 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005347 if (instr->i_jrel) {
5348 instr->i_oparg -= bsize;
5349 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005350 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005351 if (instrsize(instr->i_oparg) != isize) {
5352 extended_arg_recompile = 1;
5353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 }
5356 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 /* XXX: This is an awful hack that could hurt performance, but
5359 on the bright side it should work until we come up
5360 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 The issue is that in the first loop blocksize() is called
5363 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005364 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 So we loop until we stop seeing new EXTENDED_ARGs.
5368 The only EXTENDED_ARGs that could be popping up are
5369 ones in jump instructions. So this should converge
5370 fairly quickly.
5371 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005372 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005373}
5374
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005375static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005376dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005379 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 tuple = PyTuple_New(size);
5382 if (tuple == NULL)
5383 return NULL;
5384 while (PyDict_Next(dict, &pos, &k, &v)) {
5385 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005386 Py_INCREF(k);
5387 assert((i - offset) < size);
5388 assert((i - offset) >= 0);
5389 PyTuple_SET_ITEM(tuple, i - offset, k);
5390 }
5391 return tuple;
5392}
5393
5394static PyObject *
5395consts_dict_keys_inorder(PyObject *dict)
5396{
5397 PyObject *consts, *k, *v;
5398 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5399
5400 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5401 if (consts == NULL)
5402 return NULL;
5403 while (PyDict_Next(dict, &pos, &k, &v)) {
5404 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005405 /* The keys of the dictionary can be tuples wrapping a contant.
5406 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5407 * the object we want is always second. */
5408 if (PyTuple_CheckExact(k)) {
5409 k = PyTuple_GET_ITEM(k, 1);
5410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005412 assert(i < size);
5413 assert(i >= 0);
5414 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005416 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005417}
5418
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005419static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005423 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005425 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 if (ste->ste_nested)
5427 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005428 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005430 if (!ste->ste_generator && ste->ste_coroutine)
5431 flags |= CO_COROUTINE;
5432 if (ste->ste_generator && ste->ste_coroutine)
5433 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 if (ste->ste_varargs)
5435 flags |= CO_VARARGS;
5436 if (ste->ste_varkeywords)
5437 flags |= CO_VARKEYWORDS;
5438 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 /* (Only) inherit compilerflags in PyCF_MASK */
5441 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005444}
5445
INADA Naokic2e16072018-11-26 21:23:22 +09005446// Merge *tuple* with constant cache.
5447// Unlike merge_consts_recursive(), this function doesn't work recursively.
5448static int
5449merge_const_tuple(struct compiler *c, PyObject **tuple)
5450{
5451 assert(PyTuple_CheckExact(*tuple));
5452
5453 PyObject *key = _PyCode_ConstantKey(*tuple);
5454 if (key == NULL) {
5455 return 0;
5456 }
5457
5458 // t is borrowed reference
5459 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5460 Py_DECREF(key);
5461 if (t == NULL) {
5462 return 0;
5463 }
5464 if (t == key) { // tuple is new constant.
5465 return 1;
5466 }
5467
5468 PyObject *u = PyTuple_GET_ITEM(t, 1);
5469 Py_INCREF(u);
5470 Py_DECREF(*tuple);
5471 *tuple = u;
5472 return 1;
5473}
5474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475static PyCodeObject *
5476makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 PyObject *tmp;
5479 PyCodeObject *co = NULL;
5480 PyObject *consts = NULL;
5481 PyObject *names = NULL;
5482 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 PyObject *name = NULL;
5484 PyObject *freevars = NULL;
5485 PyObject *cellvars = NULL;
5486 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005487 Py_ssize_t nlocals;
5488 int nlocals_int;
5489 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005490 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005491
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005492 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 names = dict_keys_inorder(c->u->u_names, 0);
5494 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5495 if (!consts || !names || !varnames)
5496 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5499 if (!cellvars)
5500 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005501 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 if (!freevars)
5503 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005504
INADA Naokic2e16072018-11-26 21:23:22 +09005505 if (!merge_const_tuple(c, &names) ||
5506 !merge_const_tuple(c, &varnames) ||
5507 !merge_const_tuple(c, &cellvars) ||
5508 !merge_const_tuple(c, &freevars))
5509 {
5510 goto error;
5511 }
5512
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005513 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005514 assert(nlocals < INT_MAX);
5515 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 flags = compute_code_flags(c);
5518 if (flags < 0)
5519 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5522 if (!bytecode)
5523 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5526 if (!tmp)
5527 goto error;
5528 Py_DECREF(consts);
5529 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005530 if (!merge_const_tuple(c, &consts)) {
5531 goto error;
5532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533
Victor Stinnerf8e32212013-11-19 23:56:34 +01005534 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5535 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005536 maxdepth = stackdepth(c);
5537 if (maxdepth < 0) {
5538 goto error;
5539 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005540 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005541 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 bytecode, consts, names, varnames,
5543 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005544 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 c->u->u_firstlineno,
5546 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 Py_XDECREF(consts);
5549 Py_XDECREF(names);
5550 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 Py_XDECREF(name);
5552 Py_XDECREF(freevars);
5553 Py_XDECREF(cellvars);
5554 Py_XDECREF(bytecode);
5555 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005556}
5557
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005558
5559/* For debugging purposes only */
5560#if 0
5561static void
5562dump_instr(const struct instr *i)
5563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 const char *jrel = i->i_jrel ? "jrel " : "";
5565 const char *jabs = i->i_jabs ? "jabs " : "";
5566 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005569 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5573 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005574}
5575
5576static void
5577dump_basicblock(const basicblock *b)
5578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 const char *seen = b->b_seen ? "seen " : "";
5580 const char *b_return = b->b_return ? "return " : "";
5581 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5582 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5583 if (b->b_instr) {
5584 int i;
5585 for (i = 0; i < b->b_iused; i++) {
5586 fprintf(stderr, " [%02d] ", i);
5587 dump_instr(b->b_instr + i);
5588 }
5589 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005590}
5591#endif
5592
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005593static PyCodeObject *
5594assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 basicblock *b, *entryblock;
5597 struct assembler a;
5598 int i, j, nblocks;
5599 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 /* Make sure every block that falls off the end returns None.
5602 XXX NEXT_BLOCK() isn't quite right, because if the last
5603 block ends with a jump or return b_next shouldn't set.
5604 */
5605 if (!c->u->u_curblock->b_return) {
5606 NEXT_BLOCK(c);
5607 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005608 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 ADDOP(c, RETURN_VALUE);
5610 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 nblocks = 0;
5613 entryblock = NULL;
5614 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5615 nblocks++;
5616 entryblock = b;
5617 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 /* Set firstlineno if it wasn't explicitly set. */
5620 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005621 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5623 else
5624 c->u->u_firstlineno = 1;
5625 }
5626 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5627 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005628 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 /* Can't modify the bytecode after computing jump offsets. */
5631 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 /* Emit code in reverse postorder from dfs. */
5634 for (i = a.a_nblocks - 1; i >= 0; i--) {
5635 b = a.a_postorder[i];
5636 for (j = 0; j < b->b_iused; j++)
5637 if (!assemble_emit(&a, &b->b_instr[j]))
5638 goto error;
5639 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5642 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005643 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005647 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 assemble_free(&a);
5649 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005650}
Georg Brandl8334fd92010-12-04 10:26:46 +00005651
5652#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005653PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005654PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5655 PyArena *arena)
5656{
5657 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5658}