blob: 45e78cb22cd82437d6c430732fad1f440e4a1f20 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
67 unsigned b_seen : 1;
68 /* b_return is true if a RETURN_VALUE opcode is inserted. */
69 unsigned b_return : 1;
70 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
73 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020083enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
84 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020089 /* (optional) type-specific exit or cleanup block */
90 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040097 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040098 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010099 COMPILER_SCOPE_COMPREHENSION,
100};
101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000102/* The following items change on entry and exit of code blocks.
103 They must be saved and restored when returning to a block.
104*/
105struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400109 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100110 int u_scope_type;
111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* The following fields are dicts that map objects to
113 the index of them in co_XXX. The index is used as
114 the argument for opcodes that refer to those collections.
115 */
116 PyObject *u_consts; /* all constants */
117 PyObject *u_names; /* all names */
118 PyObject *u_varnames; /* local variables */
119 PyObject *u_cellvars; /* cell variables */
120 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Victor Stinnerf8e32212013-11-19 23:56:34 +0100124 Py_ssize_t u_argcount; /* number of arguments for block */
125 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 /* Pointer to the most recently allocated block. By following b_list
127 members, you can reach all early allocated blocks. */
128 basicblock *u_blocks;
129 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int u_nfblocks;
132 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 int u_firstlineno; /* the first lineno of the block */
135 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000136 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_lineno_set; /* boolean to indicate whether instr
138 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139};
140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000146
147Note that we don't track recursion levels during compilation - the
148task of detecting and rejecting excessive levels of nesting is
149handled by the symbol analysis pass.
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151*/
152
153struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200154 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 struct symtable *c_st;
156 PyFutureFeatures *c_future; /* pointer to module's __future__ */
157 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Georg Brandl8334fd92010-12-04 10:26:46 +0000159 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 int c_interactive; /* true if in interactive mode */
161 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
INADA Naokic2e16072018-11-26 21:23:22 +0900163 PyObject *c_const_cache; /* Python dict holding all constants,
164 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 struct compiler_unit *u; /* compiler state for current block */
166 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
167 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168};
169
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100170static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static void compiler_free(struct compiler *);
172static basicblock *compiler_new_block(struct compiler *);
173static int compiler_next_instr(struct compiler *, basicblock *);
174static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100175static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_error(struct compiler *, const char *);
Serhiy Storchakad31e7732018-10-21 10:09:39 +0300178static int compiler_warn(struct compiler *, const char *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
180
181static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
182static int compiler_visit_stmt(struct compiler *, stmt_ty);
183static int compiler_visit_keyword(struct compiler *, keyword_ty);
184static int compiler_visit_expr(struct compiler *, expr_ty);
185static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700186static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200191static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500193static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400194static int compiler_async_with(struct compiler *, stmt_ty, int);
195static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100196static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400198 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500199static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400200static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000201
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700202static int compiler_sync_comprehension_generator(
203 struct compiler *c,
204 asdl_seq *generators, int gen_index,
205 expr_ty elt, expr_ty val, int type);
206
207static int compiler_async_comprehension_generator(
208 struct compiler *c,
209 asdl_seq *generators, int gen_index,
210 expr_ty elt, expr_ty val, int type);
211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000213static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400215#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Name mangling: __private becomes _classname__private.
221 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200222 PyObject *result;
223 size_t nlen, plen, ipriv;
224 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200226 PyUnicode_READ_CHAR(ident, 0) != '_' ||
227 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_INCREF(ident);
229 return ident;
230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200231 nlen = PyUnicode_GET_LENGTH(ident);
232 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 The only time a name with a dot can occur is when
236 we are compiling an import statement that has a
237 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 TODO(jhylton): Decide whether we want to support
240 mangling of the module name, e.g. __M.X.
241 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
243 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
244 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle __whatever__ */
247 }
248 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 ipriv = 0;
250 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
251 ipriv++;
252 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_INCREF(ident);
254 return ident; /* Don't mangle if class is just underscores */
255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Antoine Pitrou55bff892013-04-06 21:21:04 +0200258 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
259 PyErr_SetString(PyExc_OverflowError,
260 "private identifier too large to be mangled");
261 return NULL;
262 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
265 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
266 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
267
268 result = PyUnicode_New(1 + nlen + plen, maxchar);
269 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
272 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200273 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
274 Py_DECREF(result);
275 return NULL;
276 }
277 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
278 Py_DECREF(result);
279 return NULL;
280 }
Victor Stinner8f825062012-04-27 13:55:39 +0200281 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000283}
284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285static int
286compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000289
INADA Naokic2e16072018-11-26 21:23:22 +0900290 c->c_const_cache = PyDict_New();
291 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900293 }
294
295 c->c_stack = PyList_New(0);
296 if (!c->c_stack) {
297 Py_CLEAR(c->c_const_cache);
298 return 0;
299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302}
303
304PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200305PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
306 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 struct compiler c;
309 PyCodeObject *co = NULL;
310 PyCompilerFlags local_flags;
311 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!__doc__) {
314 __doc__ = PyUnicode_InternFromString("__doc__");
315 if (!__doc__)
316 return NULL;
317 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000318 if (!__annotations__) {
319 __annotations__ = PyUnicode_InternFromString("__annotations__");
320 if (!__annotations__)
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!compiler_init(&c))
324 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 c.c_filename = filename;
327 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200328 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (c.c_future == NULL)
330 goto finally;
331 if (!flags) {
332 local_flags.cf_flags = 0;
333 flags = &local_flags;
334 }
335 merged = c.c_future->ff_features | flags->cf_flags;
336 c.c_future->ff_features = merged;
337 flags->cf_flags = merged;
338 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000339 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200342 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900343 goto finally;
344 }
345
Victor Stinner14e461d2013-08-26 22:28:21 +0200346 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (c.c_st == NULL) {
348 if (!PyErr_Occurred())
349 PyErr_SetString(PyExc_SystemError, "no symtable");
350 goto finally;
351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Thomas Wouters1175c432006-02-27 22:49:54 +0000355 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 compiler_free(&c);
357 assert(co || PyErr_Occurred());
358 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359}
360
361PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200362PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
363 int optimize, PyArena *arena)
364{
365 PyObject *filename;
366 PyCodeObject *co;
367 filename = PyUnicode_DecodeFSDefault(filename_str);
368 if (filename == NULL)
369 return NULL;
370 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
371 Py_DECREF(filename);
372 return co;
373
374}
375
376PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377PyNode_Compile(struct _node *n, const char *filename)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyCodeObject *co = NULL;
380 mod_ty mod;
381 PyArena *arena = PyArena_New();
382 if (!arena)
383 return NULL;
384 mod = PyAST_FromNode(n, NULL, filename, arena);
385 if (mod)
386 co = PyAST_Compile(mod, filename, NULL, arena);
387 PyArena_Free(arena);
388 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000389}
390
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (c->c_st)
395 PySymtable_Free(c->c_st);
396 if (c->c_future)
397 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200398 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900399 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401}
402
Guido van Rossum79f25d91997-04-29 20:08:16 +0000403static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 Py_ssize_t i, n;
407 PyObject *v, *k;
408 PyObject *dict = PyDict_New();
409 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 n = PyList_Size(list);
412 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100413 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (!v) {
415 Py_DECREF(dict);
416 return NULL;
417 }
418 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300419 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_DECREF(v);
421 Py_DECREF(dict);
422 return NULL;
423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_DECREF(v);
425 }
426 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427}
428
429/* Return new dict containing names from src that match scope(s).
430
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000431src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433values are integers, starting at offset and increasing by one for
434each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435*/
436
437static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100438dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700440 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500442 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(offset >= 0);
445 if (dest == NULL)
446 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Meador Inge2ca63152012-07-18 14:20:11 -0500448 /* Sort the keys so that we have a deterministic order on the indexes
449 saved in the returned dictionary. These indexes are used as indexes
450 into the free and cell var storage. Therefore if they aren't
451 deterministic, then the generated bytecode is not deterministic.
452 */
453 sorted_keys = PyDict_Keys(src);
454 if (sorted_keys == NULL)
455 return NULL;
456 if (PyList_Sort(sorted_keys) != 0) {
457 Py_DECREF(sorted_keys);
458 return NULL;
459 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500460 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500461
462 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* XXX this should probably be a macro in symtable.h */
464 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500465 k = PyList_GET_ITEM(sorted_keys, key_i);
466 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 assert(PyLong_Check(v));
468 vi = PyLong_AS_LONG(v);
469 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300472 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500474 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_DECREF(dest);
476 return NULL;
477 }
478 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300479 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500480 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_DECREF(item);
482 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
484 }
485 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 }
487 }
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000490}
491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492static void
493compiler_unit_check(struct compiler_unit *u)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 basicblock *block;
496 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700497 assert((uintptr_t)block != 0xcbcbcbcbU);
498 assert((uintptr_t)block != 0xfbfbfbfbU);
499 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (block->b_instr != NULL) {
501 assert(block->b_ialloc > 0);
502 assert(block->b_iused > 0);
503 assert(block->b_ialloc >= block->b_iused);
504 }
505 else {
506 assert (block->b_iused == 0);
507 assert (block->b_ialloc == 0);
508 }
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510}
511
512static void
513compiler_unit_free(struct compiler_unit *u)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 compiler_unit_check(u);
518 b = u->u_blocks;
519 while (b != NULL) {
520 if (b->b_instr)
521 PyObject_Free((void *)b->b_instr);
522 next = b->b_list;
523 PyObject_Free((void *)b);
524 b = next;
525 }
526 Py_CLEAR(u->u_ste);
527 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400528 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 Py_CLEAR(u->u_consts);
530 Py_CLEAR(u->u_names);
531 Py_CLEAR(u->u_varnames);
532 Py_CLEAR(u->u_freevars);
533 Py_CLEAR(u->u_cellvars);
534 Py_CLEAR(u->u_private);
535 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100539compiler_enter_scope(struct compiler *c, identifier name,
540 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100543 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
546 struct compiler_unit));
547 if (!u) {
548 PyErr_NoMemory();
549 return 0;
550 }
551 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100552 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u->u_argcount = 0;
554 u->u_kwonlyargcount = 0;
555 u->u_ste = PySymtable_Lookup(c->c_st, key);
556 if (!u->u_ste) {
557 compiler_unit_free(u);
558 return 0;
559 }
560 Py_INCREF(name);
561 u->u_name = name;
562 u->u_varnames = list2dict(u->u_ste->ste_varnames);
563 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
564 if (!u->u_varnames || !u->u_cellvars) {
565 compiler_unit_free(u);
566 return 0;
567 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000569 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500570 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300571 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 int res;
573 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200574 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 name = _PyUnicode_FromId(&PyId___class__);
576 if (!name) {
577 compiler_unit_free(u);
578 return 0;
579 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 if (res < 0) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200588 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!u->u_freevars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_blocks = NULL;
595 u->u_nfblocks = 0;
596 u->u_firstlineno = lineno;
597 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000598 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_lineno_set = 0;
600 u->u_consts = PyDict_New();
601 if (!u->u_consts) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 u->u_names = PyDict_New();
606 if (!u->u_names) {
607 compiler_unit_free(u);
608 return 0;
609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Push the old compiler_unit on the stack. */
614 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400615 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
617 Py_XDECREF(capsule);
618 compiler_unit_free(u);
619 return 0;
620 }
621 Py_DECREF(capsule);
622 u->u_private = c->u->u_private;
623 Py_XINCREF(u->u_private);
624 }
625 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100628
629 block = compiler_new_block(c);
630 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100632 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400634 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
635 if (!compiler_set_qualname(c))
636 return 0;
637 }
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640}
641
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643compiler_exit_scope(struct compiler *c)
644{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100645 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 c->c_nestlevel--;
649 compiler_unit_free(c->u);
650 /* Restore c->u to the parent unit. */
651 n = PyList_GET_SIZE(c->c_stack) - 1;
652 if (n >= 0) {
653 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400654 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 assert(c->u);
656 /* we are deleting from a list so this really shouldn't fail */
657 if (PySequence_DelItem(c->c_stack, n) < 0)
658 Py_FatalError("compiler_exit_scope()");
659 compiler_unit_check(c->u);
660 }
661 else
662 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666static int
667compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 _Py_static_string(dot_locals, ".<locals>");
671 Py_ssize_t stack_size;
672 struct compiler_unit *u = c->u;
673 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400677 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 if (stack_size > 1) {
679 int scope, force_global = 0;
680 struct compiler_unit *parent;
681 PyObject *mangled, *capsule;
682
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400683 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(parent);
686
Yury Selivanov75445082015-05-11 22:57:16 -0400687 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 assert(u->u_name);
691 mangled = _Py_Mangle(parent->u_private, u->u_name);
692 if (!mangled)
693 return 0;
694 scope = PyST_GetScope(parent->u_ste, mangled);
695 Py_DECREF(mangled);
696 assert(scope != GLOBAL_IMPLICIT);
697 if (scope == GLOBAL_EXPLICIT)
698 force_global = 1;
699 }
700
701 if (!force_global) {
702 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400703 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
705 dot_locals_str = _PyUnicode_FromId(&dot_locals);
706 if (dot_locals_str == NULL)
707 return 0;
708 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
709 if (base == NULL)
710 return 0;
711 }
712 else {
713 Py_INCREF(parent->u_qualname);
714 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400715 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100716 }
717 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 if (base != NULL) {
720 dot_str = _PyUnicode_FromId(&dot);
721 if (dot_str == NULL) {
722 Py_DECREF(base);
723 return 0;
724 }
725 name = PyUnicode_Concat(base, dot_str);
726 Py_DECREF(base);
727 if (name == NULL)
728 return 0;
729 PyUnicode_Append(&name, u->u_name);
730 if (name == NULL)
731 return 0;
732 }
733 else {
734 Py_INCREF(u->u_name);
735 name = u->u_name;
736 }
737 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100738
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400739 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740}
741
Eric V. Smith235a6f02015-09-19 14:51:32 -0400742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743/* Allocate a new block and return a pointer to it.
744 Returns NULL on error.
745*/
746
747static basicblock *
748compiler_new_block(struct compiler *c)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 basicblock *b;
751 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 u = c->u;
754 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
755 if (b == NULL) {
756 PyErr_NoMemory();
757 return NULL;
758 }
759 memset((void *)b, 0, sizeof(basicblock));
760 /* Extend the singly linked list of blocks with new block. */
761 b->b_list = u->u_blocks;
762 u->u_blocks = b;
763 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764}
765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767compiler_next_block(struct compiler *c)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 basicblock *block = compiler_new_block(c);
770 if (block == NULL)
771 return NULL;
772 c->u->u_curblock->b_next = block;
773 c->u->u_curblock = block;
774 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
777static basicblock *
778compiler_use_next_block(struct compiler *c, basicblock *block)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 assert(block != NULL);
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786/* Returns the offset of the next instruction in the current block's
787 b_instr array. Resizes the b_instr as necessary.
788 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790
791static int
792compiler_next_instr(struct compiler *c, basicblock *b)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(b != NULL);
795 if (b->b_instr == NULL) {
796 b->b_instr = (struct instr *)PyObject_Malloc(
797 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
798 if (b->b_instr == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 b->b_ialloc = DEFAULT_BLOCK_SIZE;
803 memset((char *)b->b_instr, 0,
804 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
805 }
806 else if (b->b_iused == b->b_ialloc) {
807 struct instr *tmp;
808 size_t oldsize, newsize;
809 oldsize = b->b_ialloc * sizeof(struct instr);
810 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700812 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyErr_NoMemory();
814 return -1;
815 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (newsize == 0) {
818 PyErr_NoMemory();
819 return -1;
820 }
821 b->b_ialloc <<= 1;
822 tmp = (struct instr *)PyObject_Realloc(
823 (void *)b->b_instr, newsize);
824 if (tmp == NULL) {
825 PyErr_NoMemory();
826 return -1;
827 }
828 b->b_instr = tmp;
829 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
830 }
831 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832}
833
Christian Heimes2202f872008-02-06 14:31:34 +0000834/* Set the i_lineno member of the instruction at offset off if the
835 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836 already been set. If it has been set, the call has no effect.
837
Christian Heimes2202f872008-02-06 14:31:34 +0000838 The line number is reset in the following cases:
839 - when entering a new scope
840 - on each statement
841 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200842 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000843 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846static void
847compiler_set_lineno(struct compiler *c, int off)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 basicblock *b;
850 if (c->u->u_lineno_set)
851 return;
852 c->u->u_lineno_set = 1;
853 b = c->u->u_curblock;
854 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855}
856
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200857/* Return the stack effect of opcode with argument oparg.
858
859 Some opcodes have different stack effect when jump to the target and
860 when not jump. The 'jump' parameter specifies the case:
861
862 * 0 -- when not jump
863 * 1 -- when jump
864 * -1 -- maximal
865 */
866/* XXX Make the stack effect of WITH_CLEANUP_START and
867 WITH_CLEANUP_FINISH deterministic. */
868static int
869stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300872 case NOP:
873 case EXTENDED_ARG:
874 return 0;
875
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200876 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case POP_TOP:
878 return -1;
879 case ROT_TWO:
880 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200881 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return 0;
883 case DUP_TOP:
884 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000885 case DUP_TOP_TWO:
886 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case UNARY_POSITIVE:
890 case UNARY_NEGATIVE:
891 case UNARY_NOT:
892 case UNARY_INVERT:
893 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case SET_ADD:
896 case LIST_APPEND:
897 return -1;
898 case MAP_ADD:
899 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000900
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case BINARY_POWER:
903 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400904 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case BINARY_MODULO:
906 case BINARY_ADD:
907 case BINARY_SUBTRACT:
908 case BINARY_SUBSCR:
909 case BINARY_FLOOR_DIVIDE:
910 case BINARY_TRUE_DIVIDE:
911 return -1;
912 case INPLACE_FLOOR_DIVIDE:
913 case INPLACE_TRUE_DIVIDE:
914 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case INPLACE_ADD:
917 case INPLACE_SUBTRACT:
918 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400919 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case INPLACE_MODULO:
921 return -1;
922 case STORE_SUBSCR:
923 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case DELETE_SUBSCR:
925 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case BINARY_LSHIFT:
928 case BINARY_RSHIFT:
929 case BINARY_AND:
930 case BINARY_XOR:
931 case BINARY_OR:
932 return -1;
933 case INPLACE_POWER:
934 return -1;
935 case GET_ITER:
936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case PRINT_EXPR:
939 return -1;
940 case LOAD_BUILD_CLASS:
941 return 1;
942 case INPLACE_LSHIFT:
943 case INPLACE_RSHIFT:
944 case INPLACE_AND:
945 case INPLACE_XOR:
946 case INPLACE_OR:
947 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200950 /* 1 in the normal flow.
951 * Restore the stack position and push 6 values before jumping to
952 * the handler if an exception be raised. */
953 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400954 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400956 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200957 /* Pop a variable number of values pushed by WITH_CLEANUP_START
958 * + __exit__ or __aexit__. */
959 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case RETURN_VALUE:
961 return -1;
962 case IMPORT_STAR:
963 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700964 case SETUP_ANNOTATIONS:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case YIELD_VALUE:
967 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500968 case YIELD_FROM:
969 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case POP_BLOCK:
971 return 0;
972 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200973 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200975 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 /* Pop 6 values when an exception was raised. */
977 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case STORE_NAME:
980 return -1;
981 case DELETE_NAME:
982 return 0;
983 case UNPACK_SEQUENCE:
984 return oparg-1;
985 case UNPACK_EX:
986 return (oparg&0xFF) + (oparg>>8);
987 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200988 /* -1 at end of iterator, 1 if continue iterating. */
989 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 case STORE_ATTR:
992 return -2;
993 case DELETE_ATTR:
994 return -1;
995 case STORE_GLOBAL:
996 return -1;
997 case DELETE_GLOBAL:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_CONST:
1000 return 1;
1001 case LOAD_NAME:
1002 return 1;
1003 case BUILD_TUPLE:
1004 case BUILD_LIST:
1005 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001006 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001008 case BUILD_LIST_UNPACK:
1009 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001010 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_SET_UNPACK:
1012 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001014 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001016 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001017 case BUILD_CONST_KEY_MAP:
1018 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case LOAD_ATTR:
1020 return 0;
1021 case COMPARE_OP:
1022 return -1;
1023 case IMPORT_NAME:
1024 return -1;
1025 case IMPORT_FROM:
1026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001028 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_ABSOLUTE:
1031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 case JUMP_IF_TRUE_OR_POP:
1034 case JUMP_IF_FALSE_OR_POP:
1035 return jump ? 0 : -1;
1036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case POP_JUMP_IF_FALSE:
1038 case POP_JUMP_IF_TRUE:
1039 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_GLOBAL:
1042 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001044 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001046 /* 0 in the normal flow.
1047 * Restore the stack position and push 6 values before jumping to
1048 * the handler if an exception be raised. */
1049 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001050 case BEGIN_FINALLY:
1051 /* Actually pushes 1 value, but count 6 for balancing with
1052 * END_FINALLY and POP_FINALLY.
1053 * This is the main reason of using this opcode instead of
1054 * "LOAD_CONST None". */
1055 return 6;
1056 case CALL_FINALLY:
1057 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case LOAD_FAST:
1060 return 1;
1061 case STORE_FAST:
1062 return -1;
1063 case DELETE_FAST:
1064 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 case RAISE_VARARGS:
1067 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001068
1069 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001071 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001072 case CALL_METHOD:
1073 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001075 return -oparg-1;
1076 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001077 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001078 case MAKE_FUNCTION:
1079 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1080 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 case BUILD_SLICE:
1082 if (oparg == 3)
1083 return -2;
1084 else
1085 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001087 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 case LOAD_CLOSURE:
1089 return 1;
1090 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001091 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return 1;
1093 case STORE_DEREF:
1094 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001095 case DELETE_DEREF:
1096 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001097
1098 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001099 case GET_AWAITABLE:
1100 return 0;
1101 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001102 /* 0 in the normal flow.
1103 * Restore the stack position to the position before the result
1104 * of __aenter__ and push 6 values before jumping to the handler
1105 * if an exception be raised. */
1106 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001107 case BEFORE_ASYNC_WITH:
1108 return 1;
1109 case GET_AITER:
1110 return 0;
1111 case GET_ANEXT:
1112 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001113 case GET_YIELD_FROM_ITER:
1114 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001115 case END_ASYNC_FOR:
1116 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001117 case FORMAT_VALUE:
1118 /* If there's a fmt_spec on the stack, we go from 2->1,
1119 else 1->1. */
1120 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001121 case LOAD_METHOD:
1122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001124 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
Larry Hastings3a907972013-11-23 14:49:22 -08001126 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127}
1128
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001129int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001130PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1131{
1132 return stack_effect(opcode, oparg, jump);
1133}
1134
1135int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001136PyCompile_OpcodeStackEffect(int opcode, int oparg)
1137{
1138 return stack_effect(opcode, oparg, -1);
1139}
1140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141/* Add an opcode with no argument.
1142 Returns 0 on failure, 1 on success.
1143*/
1144
1145static int
1146compiler_addop(struct compiler *c, int opcode)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 basicblock *b;
1149 struct instr *i;
1150 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001151 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 off = compiler_next_instr(c, c->u->u_curblock);
1153 if (off < 0)
1154 return 0;
1155 b = c->u->u_curblock;
1156 i = &b->b_instr[off];
1157 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001158 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (opcode == RETURN_VALUE)
1160 b->b_return = 1;
1161 compiler_set_lineno(c, off);
1162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163}
1164
Victor Stinnerf8e32212013-11-19 23:56:34 +01001165static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1167{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001168 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001173 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001175 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001176 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return -1;
1180 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_DECREF(v);
1183 return -1;
1184 }
1185 Py_DECREF(v);
1186 }
1187 else
1188 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001189 return arg;
1190}
1191
INADA Naokic2e16072018-11-26 21:23:22 +09001192// Merge const *o* recursively and return constant key object.
1193static PyObject*
1194merge_consts_recursive(struct compiler *c, PyObject *o)
1195{
1196 // None and Ellipsis are singleton, and key is the singleton.
1197 // No need to merge object and key.
1198 if (o == Py_None || o == Py_Ellipsis) {
1199 Py_INCREF(o);
1200 return o;
1201 }
1202
1203 PyObject *key = _PyCode_ConstantKey(o);
1204 if (key == NULL) {
1205 return NULL;
1206 }
1207
1208 // t is borrowed reference
1209 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1210 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001211 // o is registered in c_const_cache. Just use it.
INADA Naokic2e16072018-11-26 21:23:22 +09001212 Py_INCREF(t);
1213 Py_DECREF(key);
1214 return t;
1215 }
1216
INADA Naokif7e4d362018-11-29 00:58:46 +09001217 // We registered o in c_const_cache.
1218 // When o is a tuple or frozenset, we want to merge it's
1219 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001220 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 Py_ssize_t len = PyTuple_GET_SIZE(o);
1222 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001223 PyObject *item = PyTuple_GET_ITEM(o, i);
1224 PyObject *u = merge_consts_recursive(c, item);
1225 if (u == NULL) {
1226 Py_DECREF(key);
1227 return NULL;
1228 }
1229
1230 // See _PyCode_ConstantKey()
1231 PyObject *v; // borrowed
1232 if (PyTuple_CheckExact(u)) {
1233 v = PyTuple_GET_ITEM(u, 1);
1234 }
1235 else {
1236 v = u;
1237 }
1238 if (v != item) {
1239 Py_INCREF(v);
1240 PyTuple_SET_ITEM(o, i, v);
1241 Py_DECREF(item);
1242 }
1243
1244 Py_DECREF(u);
1245 }
1246 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001247 else if (PyFrozenSet_CheckExact(o)) {
1248 // *key* is tuple. And it's first item is frozenset of
1249 // constant keys.
1250 // See _PyCode_ConstantKey() for detail.
1251 assert(PyTuple_CheckExact(key));
1252 assert(PyTuple_GET_SIZE(key) == 2);
1253
1254 Py_ssize_t len = PySet_GET_SIZE(o);
1255 if (len == 0) { // empty frozenset should not be re-created.
1256 return key;
1257 }
1258 PyObject *tuple = PyTuple_New(len);
1259 if (tuple == NULL) {
1260 Py_DECREF(key);
1261 return NULL;
1262 }
1263 Py_ssize_t i = 0, pos = 0;
1264 PyObject *item;
1265 Py_hash_t hash;
1266 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1267 PyObject *k = merge_consts_recursive(c, item);
1268 if (k == NULL) {
1269 Py_DECREF(tuple);
1270 Py_DECREF(key);
1271 return NULL;
1272 }
1273 PyObject *u;
1274 if (PyTuple_CheckExact(k)) {
1275 u = PyTuple_GET_ITEM(k, 1);
1276 Py_INCREF(u);
1277 Py_DECREF(k);
1278 }
1279 else {
1280 u = k;
1281 }
1282 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1283 i++;
1284 }
1285
1286 // Instead of rewriting o, we create new frozenset and embed in the
1287 // key tuple. Caller should get merged frozenset from the key tuple.
1288 PyObject *new = PyFrozenSet_New(tuple);
1289 Py_DECREF(tuple);
1290 if (new == NULL) {
1291 Py_DECREF(key);
1292 return NULL;
1293 }
1294 assert(PyTuple_GET_ITEM(key, 1) == o);
1295 Py_DECREF(o);
1296 PyTuple_SET_ITEM(key, 1, new);
1297 }
INADA Naokic2e16072018-11-26 21:23:22 +09001298
1299 return key;
1300}
1301
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001302static Py_ssize_t
1303compiler_add_const(struct compiler *c, PyObject *o)
1304{
INADA Naokic2e16072018-11-26 21:23:22 +09001305 PyObject *key = merge_consts_recursive(c, o);
1306 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001308 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001309
INADA Naokic2e16072018-11-26 21:23:22 +09001310 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1311 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
1315static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316compiler_addop_load_const(struct compiler *c, PyObject *o)
1317{
1318 Py_ssize_t arg = compiler_add_const(c, o);
1319 if (arg < 0)
1320 return 0;
1321 return compiler_addop_i(c, LOAD_CONST, arg);
1322}
1323
1324static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001328 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 return compiler_addop_i(c, opcode, arg);
1332}
1333
1334static int
1335compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001338 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1340 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 arg = compiler_add_o(c, dict, mangled);
1343 Py_DECREF(mangled);
1344 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 return compiler_addop_i(c, opcode, arg);
1347}
1348
1349/* Add an opcode with an integer argument.
1350 Returns 0 on failure, 1 on success.
1351*/
1352
1353static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001354compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 struct instr *i;
1357 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358
Victor Stinner2ad474b2016-03-01 23:34:47 +01001359 /* oparg value is unsigned, but a signed C int is usually used to store
1360 it in the C code (like Python/ceval.c).
1361
1362 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1363
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001364 The argument of a concrete bytecode instruction is limited to 8-bit.
1365 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1366 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001367 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 off = compiler_next_instr(c, c->u->u_curblock);
1370 if (off < 0)
1371 return 0;
1372 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001373 i->i_opcode = opcode;
1374 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 compiler_set_lineno(c, off);
1376 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377}
1378
1379static int
1380compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 struct instr *i;
1383 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001385 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 assert(b != NULL);
1387 off = compiler_next_instr(c, c->u->u_curblock);
1388 if (off < 0)
1389 return 0;
1390 i = &c->u->u_curblock->b_instr[off];
1391 i->i_opcode = opcode;
1392 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (absolute)
1394 i->i_jabs = 1;
1395 else
1396 i->i_jrel = 1;
1397 compiler_set_lineno(c, off);
1398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399}
1400
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001401/* NEXT_BLOCK() creates an implicit jump from the current block
1402 to the new block.
1403
1404 The returns inside this macro make it impossible to decref objects
1405 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (compiler_next_block((C)) == NULL) \
1409 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
1412#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!compiler_addop((C), (OP))) \
1414 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415}
1416
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001417#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!compiler_addop((C), (OP))) { \
1419 compiler_exit_scope(c); \
1420 return 0; \
1421 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001422}
1423
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001424#define ADDOP_LOAD_CONST(C, O) { \
1425 if (!compiler_addop_load_const((C), (O))) \
1426 return 0; \
1427}
1428
1429/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1430#define ADDOP_LOAD_CONST_NEW(C, O) { \
1431 PyObject *__new_const = (O); \
1432 if (__new_const == NULL) { \
1433 return 0; \
1434 } \
1435 if (!compiler_addop_load_const((C), __new_const)) { \
1436 Py_DECREF(__new_const); \
1437 return 0; \
1438 } \
1439 Py_DECREF(__new_const); \
1440}
1441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1444 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001447/* Same as ADDOP_O, but steals a reference. */
1448#define ADDOP_N(C, OP, O, TYPE) { \
1449 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1450 Py_DECREF((O)); \
1451 return 0; \
1452 } \
1453 Py_DECREF((O)); \
1454}
1455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1458 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459}
1460
1461#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_addop_i((C), (OP), (O))) \
1463 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_j((C), (OP), (O), 1)) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_j((C), (OP), (O), 0)) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
1476/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1477 the ASDL name to synthesize the name of the C type and the visit function.
1478*/
1479
1480#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_visit_ ## TYPE((C), (V))) \
1482 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483}
1484
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001485#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_visit_ ## TYPE((C), (V))) { \
1487 compiler_exit_scope(c); \
1488 return 0; \
1489 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001490}
1491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!compiler_visit_slice((C), (V), (CTX))) \
1494 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495}
1496
1497#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 int _i; \
1499 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1500 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1501 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1502 if (!compiler_visit_ ## TYPE((C), elt)) \
1503 return 0; \
1504 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001507#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 int _i; \
1509 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1510 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1511 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1512 if (!compiler_visit_ ## TYPE((C), elt)) { \
1513 compiler_exit_scope(c); \
1514 return 0; \
1515 } \
1516 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001517}
1518
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001519/* Search if variable annotations are present statically in a block. */
1520
1521static int
1522find_ann(asdl_seq *stmts)
1523{
1524 int i, j, res = 0;
1525 stmt_ty st;
1526
1527 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1528 st = (stmt_ty)asdl_seq_GET(stmts, i);
1529 switch (st->kind) {
1530 case AnnAssign_kind:
1531 return 1;
1532 case For_kind:
1533 res = find_ann(st->v.For.body) ||
1534 find_ann(st->v.For.orelse);
1535 break;
1536 case AsyncFor_kind:
1537 res = find_ann(st->v.AsyncFor.body) ||
1538 find_ann(st->v.AsyncFor.orelse);
1539 break;
1540 case While_kind:
1541 res = find_ann(st->v.While.body) ||
1542 find_ann(st->v.While.orelse);
1543 break;
1544 case If_kind:
1545 res = find_ann(st->v.If.body) ||
1546 find_ann(st->v.If.orelse);
1547 break;
1548 case With_kind:
1549 res = find_ann(st->v.With.body);
1550 break;
1551 case AsyncWith_kind:
1552 res = find_ann(st->v.AsyncWith.body);
1553 break;
1554 case Try_kind:
1555 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1556 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1557 st->v.Try.handlers, j);
1558 if (find_ann(handler->v.ExceptHandler.body)) {
1559 return 1;
1560 }
1561 }
1562 res = find_ann(st->v.Try.body) ||
1563 find_ann(st->v.Try.finalbody) ||
1564 find_ann(st->v.Try.orelse);
1565 break;
1566 default:
1567 res = 0;
1568 }
1569 if (res) {
1570 break;
1571 }
1572 }
1573 return res;
1574}
1575
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001576/*
1577 * Frame block handling functions
1578 */
1579
1580static int
1581compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1582 basicblock *exit)
1583{
1584 struct fblockinfo *f;
1585 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1586 PyErr_SetString(PyExc_SyntaxError,
1587 "too many statically nested blocks");
1588 return 0;
1589 }
1590 f = &c->u->u_fblock[c->u->u_nfblocks++];
1591 f->fb_type = t;
1592 f->fb_block = b;
1593 f->fb_exit = exit;
1594 return 1;
1595}
1596
1597static void
1598compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1599{
1600 struct compiler_unit *u = c->u;
1601 assert(u->u_nfblocks > 0);
1602 u->u_nfblocks--;
1603 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1604 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1605}
1606
1607/* Unwind a frame block. If preserve_tos is true, the TOS before
1608 * popping the blocks will be restored afterwards.
1609 */
1610static int
1611compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1612 int preserve_tos)
1613{
1614 switch (info->fb_type) {
1615 case WHILE_LOOP:
1616 return 1;
1617
1618 case FINALLY_END:
1619 ADDOP_I(c, POP_FINALLY, preserve_tos);
1620 return 1;
1621
1622 case FOR_LOOP:
1623 /* Pop the iterator */
1624 if (preserve_tos) {
1625 ADDOP(c, ROT_TWO);
1626 }
1627 ADDOP(c, POP_TOP);
1628 return 1;
1629
1630 case EXCEPT:
1631 ADDOP(c, POP_BLOCK);
1632 return 1;
1633
1634 case FINALLY_TRY:
1635 ADDOP(c, POP_BLOCK);
1636 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1637 return 1;
1638
1639 case WITH:
1640 case ASYNC_WITH:
1641 ADDOP(c, POP_BLOCK);
1642 if (preserve_tos) {
1643 ADDOP(c, ROT_TWO);
1644 }
1645 ADDOP(c, BEGIN_FINALLY);
1646 ADDOP(c, WITH_CLEANUP_START);
1647 if (info->fb_type == ASYNC_WITH) {
1648 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001649 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001650 ADDOP(c, YIELD_FROM);
1651 }
1652 ADDOP(c, WITH_CLEANUP_FINISH);
1653 ADDOP_I(c, POP_FINALLY, 0);
1654 return 1;
1655
1656 case HANDLER_CLEANUP:
1657 if (preserve_tos) {
1658 ADDOP(c, ROT_FOUR);
1659 }
1660 if (info->fb_exit) {
1661 ADDOP(c, POP_BLOCK);
1662 ADDOP(c, POP_EXCEPT);
1663 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1664 }
1665 else {
1666 ADDOP(c, POP_EXCEPT);
1667 }
1668 return 1;
1669 }
1670 Py_UNREACHABLE();
1671}
1672
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001673/* Compile a sequence of statements, checking for a docstring
1674 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
1676static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001677compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001679 int i = 0;
1680 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001681 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001682
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001683 /* Set current line number to the line number of first statement.
1684 This way line number for SETUP_ANNOTATIONS will always
1685 coincide with the line number of first "real" statement in module.
1686 If body is empy, then lineno will be set later in assemble. */
1687 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1688 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001689 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001690 c->u->u_lineno = st->lineno;
1691 }
1692 /* Every annotated class and module should have __annotations__. */
1693 if (find_ann(stmts)) {
1694 ADDOP(c, SETUP_ANNOTATIONS);
1695 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001696 if (!asdl_seq_LEN(stmts))
1697 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001698 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001699 if (c->c_optimize < 2) {
1700 docstring = _PyAST_GetDocString(stmts);
1701 if (docstring) {
1702 i = 1;
1703 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1704 assert(st->kind == Expr_kind);
1705 VISIT(c, expr, st->v.Expr.value);
1706 if (!compiler_nameop(c, __doc__, Store))
1707 return 0;
1708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001710 for (; i < asdl_seq_LEN(stmts); i++)
1711 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713}
1714
1715static PyCodeObject *
1716compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyCodeObject *co;
1719 int addNone = 1;
1720 static PyObject *module;
1721 if (!module) {
1722 module = PyUnicode_InternFromString("<module>");
1723 if (!module)
1724 return NULL;
1725 }
1726 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001727 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return NULL;
1729 switch (mod->kind) {
1730 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001731 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 compiler_exit_scope(c);
1733 return 0;
1734 }
1735 break;
1736 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001737 if (find_ann(mod->v.Interactive.body)) {
1738 ADDOP(c, SETUP_ANNOTATIONS);
1739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 c->c_interactive = 1;
1741 VISIT_SEQ_IN_SCOPE(c, stmt,
1742 mod->v.Interactive.body);
1743 break;
1744 case Expression_kind:
1745 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1746 addNone = 0;
1747 break;
1748 case Suite_kind:
1749 PyErr_SetString(PyExc_SystemError,
1750 "suite should not be possible");
1751 return 0;
1752 default:
1753 PyErr_Format(PyExc_SystemError,
1754 "module kind %d should not be possible",
1755 mod->kind);
1756 return 0;
1757 }
1758 co = assemble(c, addNone);
1759 compiler_exit_scope(c);
1760 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001761}
1762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763/* The test for LOCAL must come before the test for FREE in order to
1764 handle classes where name is both local and free. The local var is
1765 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001766*/
1767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768static int
1769get_ref_type(struct compiler *c, PyObject *name)
1770{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001771 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001772 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001773 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001774 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001775 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (scope == 0) {
1777 char buf[350];
1778 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001779 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001781 PyUnicode_AsUTF8(name),
1782 PyUnicode_AsUTF8(c->u->u_name),
1783 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1784 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1785 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 );
1788 Py_FatalError(buf);
1789 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792}
1793
1794static int
1795compiler_lookup_arg(PyObject *dict, PyObject *name)
1796{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001797 PyObject *v;
1798 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001800 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001801 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802}
1803
1804static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001805compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001807 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001808 if (qualname == NULL)
1809 qualname = co->co_name;
1810
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 if (free) {
1812 for (i = 0; i < free; ++i) {
1813 /* Bypass com_addop_varname because it will generate
1814 LOAD_DEREF but LOAD_CLOSURE is needed.
1815 */
1816 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1817 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001819 /* Special case: If a class contains a method with a
1820 free variable that has the same name as a method,
1821 the name will be considered free *and* local in the
1822 class. It should be handled by the closure, as
1823 well as by the normal name loookup logic.
1824 */
1825 reftype = get_ref_type(c, name);
1826 if (reftype == CELL)
1827 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1828 else /* (reftype == FREE) */
1829 arg = compiler_lookup_arg(c->u->u_freevars, name);
1830 if (arg == -1) {
1831 fprintf(stderr,
1832 "lookup %s in %s %d %d\n"
1833 "freevars of %s: %s\n",
1834 PyUnicode_AsUTF8(PyObject_Repr(name)),
1835 PyUnicode_AsUTF8(c->u->u_name),
1836 reftype, arg,
1837 PyUnicode_AsUTF8(co->co_name),
1838 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1839 Py_FatalError("compiler_make_closure()");
1840 }
1841 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001843 flags |= 0x08;
1844 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001846 ADDOP_LOAD_CONST(c, (PyObject*)co);
1847 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
1852static int
1853compiler_decorators(struct compiler *c, asdl_seq* decos)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (!decos)
1858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1861 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1862 }
1863 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864}
1865
1866static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001867compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001869{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001870 /* Push a dict of keyword-only default values.
1871
1872 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1873 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001874 int i;
1875 PyObject *keys = NULL;
1876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1878 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1879 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1880 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001881 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001882 if (!mangled) {
1883 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 if (keys == NULL) {
1886 keys = PyList_New(1);
1887 if (keys == NULL) {
1888 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001889 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001890 }
1891 PyList_SET_ITEM(keys, 0, mangled);
1892 }
1893 else {
1894 int res = PyList_Append(keys, mangled);
1895 Py_DECREF(mangled);
1896 if (res == -1) {
1897 goto error;
1898 }
1899 }
1900 if (!compiler_visit_expr(c, default_)) {
1901 goto error;
1902 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 }
1904 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905 if (keys != NULL) {
1906 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1907 PyObject *keys_tuple = PyList_AsTuple(keys);
1908 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001909 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001911 assert(default_count > 0);
1912 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 }
1914 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001915 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 }
1917
1918error:
1919 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001920 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001921}
1922
1923static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001924compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1925{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001926 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001927 return 1;
1928}
1929
1930static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001931compiler_visit_argannotation(struct compiler *c, identifier id,
1932 expr_ty annotation, PyObject *names)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001935 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001936 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1937 VISIT(c, annexpr, annotation)
1938 }
1939 else {
1940 VISIT(c, expr, annotation);
1941 }
Victor Stinner065efc32014-02-18 22:07:56 +01001942 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001943 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001944 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001945 if (PyList_Append(names, mangled) < 0) {
1946 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001947 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001948 }
1949 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001951 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001952}
1953
1954static int
1955compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1956 PyObject *names)
1957{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001958 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 for (i = 0; i < asdl_seq_LEN(args); i++) {
1960 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001961 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 c,
1963 arg->arg,
1964 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001965 names))
1966 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001968 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001969}
1970
1971static int
1972compiler_visit_annotations(struct compiler *c, arguments_ty args,
1973 expr_ty returns)
1974{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001975 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001976 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001977
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001978 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 */
1980 static identifier return_str;
1981 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001982 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 names = PyList_New(0);
1984 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001985 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001986
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001987 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001989 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001990 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001991 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001993 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001995 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001996 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001997 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (!return_str) {
2001 return_str = PyUnicode_InternFromString("return");
2002 if (!return_str)
2003 goto error;
2004 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002005 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 goto error;
2007 }
2008
2009 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 PyObject *keytuple = PyList_AsTuple(names);
2012 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002013 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002015 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 else {
2018 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002019 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002021
2022error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002024 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002025}
2026
2027static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028compiler_visit_defaults(struct compiler *c, arguments_ty args)
2029{
2030 VISIT_SEQ(c, expr, args->defaults);
2031 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033}
2034
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002035static Py_ssize_t
2036compiler_default_arguments(struct compiler *c, arguments_ty args)
2037{
2038 Py_ssize_t funcflags = 0;
2039 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 if (!compiler_visit_defaults(c, args))
2041 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042 funcflags |= 0x01;
2043 }
2044 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002045 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002046 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002047 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002048 return -1;
2049 }
2050 else if (res > 0) {
2051 funcflags |= 0x02;
2052 }
2053 }
2054 return funcflags;
2055}
2056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057static int
Yury Selivanov75445082015-05-11 22:57:16 -04002058compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002061 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002062 arguments_ty args;
2063 expr_ty returns;
2064 identifier name;
2065 asdl_seq* decos;
2066 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002067 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002068 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002069 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002070 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071
Yury Selivanov75445082015-05-11 22:57:16 -04002072 if (is_async) {
2073 assert(s->kind == AsyncFunctionDef_kind);
2074
2075 args = s->v.AsyncFunctionDef.args;
2076 returns = s->v.AsyncFunctionDef.returns;
2077 decos = s->v.AsyncFunctionDef.decorator_list;
2078 name = s->v.AsyncFunctionDef.name;
2079 body = s->v.AsyncFunctionDef.body;
2080
2081 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2082 } else {
2083 assert(s->kind == FunctionDef_kind);
2084
2085 args = s->v.FunctionDef.args;
2086 returns = s->v.FunctionDef.returns;
2087 decos = s->v.FunctionDef.decorator_list;
2088 name = s->v.FunctionDef.name;
2089 body = s->v.FunctionDef.body;
2090
2091 scope_type = COMPILER_SCOPE_FUNCTION;
2092 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (!compiler_decorators(c, decos))
2095 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002096
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002097 firstlineno = s->lineno;
2098 if (asdl_seq_LEN(decos)) {
2099 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2100 }
2101
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002102 funcflags = compiler_default_arguments(c, args);
2103 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105 }
2106
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002107 annotations = compiler_visit_annotations(c, args, returns);
2108 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 return 0;
2110 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002111 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 funcflags |= 0x04;
2113 }
2114
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002115 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 return 0;
2117 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118
INADA Naokicb41b272017-02-23 00:31:59 +09002119 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002120 if (c->c_optimize < 2) {
2121 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002122 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002123 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 compiler_exit_scope(c);
2125 return 0;
2126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 c->u->u_argcount = asdl_seq_LEN(args->args);
2129 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002130 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002132 qualname = c->u->u_qualname;
2133 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002135 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002136 Py_XDECREF(qualname);
2137 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002139 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002142 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* decorators */
2146 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2147 ADDOP_I(c, CALL_FUNCTION, 1);
2148 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149
Yury Selivanov75445082015-05-11 22:57:16 -04002150 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151}
2152
2153static int
2154compiler_class(struct compiler *c, stmt_ty s)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyCodeObject *co;
2157 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002158 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (!compiler_decorators(c, decos))
2162 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002163
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002164 firstlineno = s->lineno;
2165 if (asdl_seq_LEN(decos)) {
2166 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2167 }
2168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* ultimately generate code for:
2170 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2171 where:
2172 <func> is a function/closure created from the class body;
2173 it has a single argument (__locals__) where the dict
2174 (or MutableSequence) representing the locals is passed
2175 <name> is the class name
2176 <bases> is the positional arguments and *varargs argument
2177 <keywords> is the keyword arguments and **kwds argument
2178 This borrows from compiler_call.
2179 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002182 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002183 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return 0;
2185 /* this block represents what we do in the new scope */
2186 {
2187 /* use the class name for name mangling */
2188 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002189 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* load (global) __name__ ... */
2191 str = PyUnicode_InternFromString("__name__");
2192 if (!str || !compiler_nameop(c, str, Load)) {
2193 Py_XDECREF(str);
2194 compiler_exit_scope(c);
2195 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_DECREF(str);
2198 /* ... and store it as __module__ */
2199 str = PyUnicode_InternFromString("__module__");
2200 if (!str || !compiler_nameop(c, str, Store)) {
2201 Py_XDECREF(str);
2202 compiler_exit_scope(c);
2203 return 0;
2204 }
2205 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002206 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002207 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002208 str = PyUnicode_InternFromString("__qualname__");
2209 if (!str || !compiler_nameop(c, str, Store)) {
2210 Py_XDECREF(str);
2211 compiler_exit_scope(c);
2212 return 0;
2213 }
2214 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002216 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 compiler_exit_scope(c);
2218 return 0;
2219 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002220 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002221 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002222 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002223 str = PyUnicode_InternFromString("__class__");
2224 if (str == NULL) {
2225 compiler_exit_scope(c);
2226 return 0;
2227 }
2228 i = compiler_lookup_arg(c->u->u_cellvars, str);
2229 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002230 if (i < 0) {
2231 compiler_exit_scope(c);
2232 return 0;
2233 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002234 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002237 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002238 str = PyUnicode_InternFromString("__classcell__");
2239 if (!str || !compiler_nameop(c, str, Store)) {
2240 Py_XDECREF(str);
2241 compiler_exit_scope(c);
2242 return 0;
2243 }
2244 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002246 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002247 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002248 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002249 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002250 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002251 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* create the code object */
2253 co = assemble(c, 1);
2254 }
2255 /* leave the new scope */
2256 compiler_exit_scope(c);
2257 if (co == NULL)
2258 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* 2. load the 'build_class' function */
2261 ADDOP(c, LOAD_BUILD_CLASS);
2262
2263 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002264 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 Py_DECREF(co);
2266
2267 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002268 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269
2270 /* 5. generate the rest of the code for the call */
2271 if (!compiler_call_helper(c, 2,
2272 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002273 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 0;
2275
2276 /* 6. apply decorators */
2277 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2278 ADDOP_I(c, CALL_FUNCTION, 1);
2279 }
2280
2281 /* 7. store into <name> */
2282 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2283 return 0;
2284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
2287static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002288cmpop(cmpop_ty op)
2289{
2290 switch (op) {
2291 case Eq:
2292 return PyCmp_EQ;
2293 case NotEq:
2294 return PyCmp_NE;
2295 case Lt:
2296 return PyCmp_LT;
2297 case LtE:
2298 return PyCmp_LE;
2299 case Gt:
2300 return PyCmp_GT;
2301 case GtE:
2302 return PyCmp_GE;
2303 case Is:
2304 return PyCmp_IS;
2305 case IsNot:
2306 return PyCmp_IS_NOT;
2307 case In:
2308 return PyCmp_IN;
2309 case NotIn:
2310 return PyCmp_NOT_IN;
2311 default:
2312 return PyCmp_BAD;
2313 }
2314}
2315
2316static int
2317compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2318{
2319 switch (e->kind) {
2320 case UnaryOp_kind:
2321 if (e->v.UnaryOp.op == Not)
2322 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2323 /* fallback to general implementation */
2324 break;
2325 case BoolOp_kind: {
2326 asdl_seq *s = e->v.BoolOp.values;
2327 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2328 assert(n >= 0);
2329 int cond2 = e->v.BoolOp.op == Or;
2330 basicblock *next2 = next;
2331 if (!cond2 != !cond) {
2332 next2 = compiler_new_block(c);
2333 if (next2 == NULL)
2334 return 0;
2335 }
2336 for (i = 0; i < n; ++i) {
2337 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2338 return 0;
2339 }
2340 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2341 return 0;
2342 if (next2 != next)
2343 compiler_use_next_block(c, next2);
2344 return 1;
2345 }
2346 case IfExp_kind: {
2347 basicblock *end, *next2;
2348 end = compiler_new_block(c);
2349 if (end == NULL)
2350 return 0;
2351 next2 = compiler_new_block(c);
2352 if (next2 == NULL)
2353 return 0;
2354 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2355 return 0;
2356 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2357 return 0;
2358 ADDOP_JREL(c, JUMP_FORWARD, end);
2359 compiler_use_next_block(c, next2);
2360 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2361 return 0;
2362 compiler_use_next_block(c, end);
2363 return 1;
2364 }
2365 case Compare_kind: {
2366 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2367 if (n > 0) {
2368 basicblock *cleanup = compiler_new_block(c);
2369 if (cleanup == NULL)
2370 return 0;
2371 VISIT(c, expr, e->v.Compare.left);
2372 for (i = 0; i < n; i++) {
2373 VISIT(c, expr,
2374 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2375 ADDOP(c, DUP_TOP);
2376 ADDOP(c, ROT_THREE);
2377 ADDOP_I(c, COMPARE_OP,
2378 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2379 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2380 NEXT_BLOCK(c);
2381 }
2382 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2383 ADDOP_I(c, COMPARE_OP,
2384 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2385 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2386 basicblock *end = compiler_new_block(c);
2387 if (end == NULL)
2388 return 0;
2389 ADDOP_JREL(c, JUMP_FORWARD, end);
2390 compiler_use_next_block(c, cleanup);
2391 ADDOP(c, POP_TOP);
2392 if (!cond) {
2393 ADDOP_JREL(c, JUMP_FORWARD, next);
2394 }
2395 compiler_use_next_block(c, end);
2396 return 1;
2397 }
2398 /* fallback to general implementation */
2399 break;
2400 }
2401 default:
2402 /* fallback to general implementation */
2403 break;
2404 }
2405
2406 /* general implementation */
2407 VISIT(c, expr, e);
2408 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2409 return 1;
2410}
2411
2412static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002413compiler_ifexp(struct compiler *c, expr_ty e)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 basicblock *end, *next;
2416
2417 assert(e->kind == IfExp_kind);
2418 end = compiler_new_block(c);
2419 if (end == NULL)
2420 return 0;
2421 next = compiler_new_block(c);
2422 if (next == NULL)
2423 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002424 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2425 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 VISIT(c, expr, e->v.IfExp.body);
2427 ADDOP_JREL(c, JUMP_FORWARD, end);
2428 compiler_use_next_block(c, next);
2429 VISIT(c, expr, e->v.IfExp.orelse);
2430 compiler_use_next_block(c, end);
2431 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002432}
2433
2434static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002435compiler_lambda(struct compiler *c, expr_ty e)
2436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002438 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002440 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 arguments_ty args = e->v.Lambda.args;
2442 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (!name) {
2445 name = PyUnicode_InternFromString("<lambda>");
2446 if (!name)
2447 return 0;
2448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002450 funcflags = compiler_default_arguments(c, args);
2451 if (funcflags == -1) {
2452 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002454
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002455 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002456 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* Make None the first constant, so the lambda can't have a
2460 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002461 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 c->u->u_argcount = asdl_seq_LEN(args->args);
2465 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2466 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2467 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002468 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 }
2470 else {
2471 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002472 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002474 qualname = c->u->u_qualname;
2475 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002477 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002480 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002481 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 Py_DECREF(co);
2483
2484 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485}
2486
2487static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488compiler_if(struct compiler *c, stmt_ty s)
2489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 basicblock *end, *next;
2491 int constant;
2492 assert(s->kind == If_kind);
2493 end = compiler_new_block(c);
2494 if (end == NULL)
2495 return 0;
2496
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002497 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 /* constant = 0: "if 0"
2499 * constant = 1: "if 1", "if 2", ...
2500 * constant = -1: rest */
2501 if (constant == 0) {
2502 if (s->v.If.orelse)
2503 VISIT_SEQ(c, stmt, s->v.If.orelse);
2504 } else if (constant == 1) {
2505 VISIT_SEQ(c, stmt, s->v.If.body);
2506 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002507 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 next = compiler_new_block(c);
2509 if (next == NULL)
2510 return 0;
2511 }
2512 else
2513 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002514 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2515 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002517 if (asdl_seq_LEN(s->v.If.orelse)) {
2518 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 compiler_use_next_block(c, next);
2520 VISIT_SEQ(c, stmt, s->v.If.orelse);
2521 }
2522 }
2523 compiler_use_next_block(c, end);
2524 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525}
2526
2527static int
2528compiler_for(struct compiler *c, stmt_ty s)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 start = compiler_new_block(c);
2533 cleanup = compiler_new_block(c);
2534 end = compiler_new_block(c);
2535 if (start == NULL || end == NULL || cleanup == NULL)
2536 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002537
2538 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 VISIT(c, expr, s->v.For.iter);
2542 ADDOP(c, GET_ITER);
2543 compiler_use_next_block(c, start);
2544 ADDOP_JREL(c, FOR_ITER, cleanup);
2545 VISIT(c, expr, s->v.For.target);
2546 VISIT_SEQ(c, stmt, s->v.For.body);
2547 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2548 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002549
2550 compiler_pop_fblock(c, FOR_LOOP, start);
2551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 VISIT_SEQ(c, stmt, s->v.For.orelse);
2553 compiler_use_next_block(c, end);
2554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555}
2556
Yury Selivanov75445082015-05-11 22:57:16 -04002557
2558static int
2559compiler_async_for(struct compiler *c, stmt_ty s)
2560{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002561 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002562 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2563 return compiler_error(c, "'async for' outside async function");
2564 }
2565
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002566 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002567 except = compiler_new_block(c);
2568 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002569
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002570 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002571 return 0;
2572
2573 VISIT(c, expr, s->v.AsyncFor.iter);
2574 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002575
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002576 compiler_use_next_block(c, start);
2577 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2578 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002579
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002580 /* SETUP_FINALLY to guard the __anext__ call */
2581 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002582 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002583 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002584 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002585 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002586
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002587 /* Success block for __anext__ */
2588 VISIT(c, expr, s->v.AsyncFor.target);
2589 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2590 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2591
2592 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002593
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002594 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002595 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002596 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002597
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002598 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002599 VISIT_SEQ(c, stmt, s->v.For.orelse);
2600
2601 compiler_use_next_block(c, end);
2602
2603 return 1;
2604}
2605
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606static int
2607compiler_while(struct compiler *c, stmt_ty s)
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002610 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 if (constant == 0) {
2613 if (s->v.While.orelse)
2614 VISIT_SEQ(c, stmt, s->v.While.orelse);
2615 return 1;
2616 }
2617 loop = compiler_new_block(c);
2618 end = compiler_new_block(c);
2619 if (constant == -1) {
2620 anchor = compiler_new_block(c);
2621 if (anchor == NULL)
2622 return 0;
2623 }
2624 if (loop == NULL || end == NULL)
2625 return 0;
2626 if (s->v.While.orelse) {
2627 orelse = compiler_new_block(c);
2628 if (orelse == NULL)
2629 return 0;
2630 }
2631 else
2632 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002635 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return 0;
2637 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002638 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2639 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 }
2641 VISIT_SEQ(c, stmt, s->v.While.body);
2642 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* XXX should the two POP instructions be in a separate block
2645 if there is no else clause ?
2646 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002648 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002650 compiler_pop_fblock(c, WHILE_LOOP, loop);
2651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 if (orelse != NULL) /* what if orelse is just pass? */
2653 VISIT_SEQ(c, stmt, s->v.While.orelse);
2654 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657}
2658
2659static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002660compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002662 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002663 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664 if (c->u->u_ste->ste_type != FunctionBlock)
2665 return compiler_error(c, "'return' outside function");
2666 if (s->v.Return.value != NULL &&
2667 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2668 {
2669 return compiler_error(
2670 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002672 if (preserve_tos) {
2673 VISIT(c, expr, s->v.Return.value);
2674 }
2675 for (int depth = c->u->u_nfblocks; depth--;) {
2676 struct fblockinfo *info = &c->u->u_fblock[depth];
2677
2678 if (!compiler_unwind_fblock(c, info, preserve_tos))
2679 return 0;
2680 }
2681 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002682 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002683 }
2684 else if (!preserve_tos) {
2685 VISIT(c, expr, s->v.Return.value);
2686 }
2687 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690}
2691
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002692static int
2693compiler_break(struct compiler *c)
2694{
2695 for (int depth = c->u->u_nfblocks; depth--;) {
2696 struct fblockinfo *info = &c->u->u_fblock[depth];
2697
2698 if (!compiler_unwind_fblock(c, info, 0))
2699 return 0;
2700 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2701 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2702 return 1;
2703 }
2704 }
2705 return compiler_error(c, "'break' outside loop");
2706}
2707
2708static int
2709compiler_continue(struct compiler *c)
2710{
2711 for (int depth = c->u->u_nfblocks; depth--;) {
2712 struct fblockinfo *info = &c->u->u_fblock[depth];
2713
2714 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2715 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2716 return 1;
2717 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002718 if (!compiler_unwind_fblock(c, info, 0))
2719 return 0;
2720 }
2721 return compiler_error(c, "'continue' not properly in loop");
2722}
2723
2724
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726
2727 SETUP_FINALLY L
2728 <code for body>
2729 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002730 BEGIN_FINALLY
2731 L:
2732 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 END_FINALLY
2734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 The special instructions use the block stack. Each block
2736 stack entry contains the instruction that created it (here
2737 SETUP_FINALLY), the level of the value stack at the time the
2738 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 Pushes the current value stack level and the label
2742 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002744 Pops en entry from the block stack.
2745 BEGIN_FINALLY
2746 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002748 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2749 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002752 when a SETUP_FINALLY entry is found, the raised and the caught
2753 exceptions are pushed onto the value stack (and the exception
2754 condition is cleared), and the interpreter jumps to the label
2755 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756*/
2757
2758static int
2759compiler_try_finally(struct compiler *c, stmt_ty s)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 body = compiler_new_block(c);
2764 end = compiler_new_block(c);
2765 if (body == NULL || end == NULL)
2766 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002768 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 ADDOP_JREL(c, SETUP_FINALLY, end);
2770 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002771 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002773 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2774 if (!compiler_try_except(c, s))
2775 return 0;
2776 }
2777 else {
2778 VISIT_SEQ(c, stmt, s->v.Try.body);
2779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002781 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002786 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002788 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 ADDOP(c, END_FINALLY);
2790 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792}
2793
2794/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002795 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 (The contents of the value stack is shown in [], with the top
2797 at the right; 'tb' is trace-back info, 'val' the exception's
2798 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799
2800 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 [] <code for S>
2803 [] POP_BLOCK
2804 [] JUMP_FORWARD L0
2805
2806 [tb, val, exc] L1: DUP )
2807 [tb, val, exc, exc] <evaluate E1> )
2808 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2809 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2810 [tb, val, exc] POP
2811 [tb, val] <assign to V1> (or POP if no V1)
2812 [tb] POP
2813 [] <code for S1>
2814 JUMP_FORWARD L0
2815
2816 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817 .............................etc.......................
2818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2820
2821 [] L0: <next statement>
2822
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002823 Of course, parts are not generated if Vi or Ei is not present.
2824*/
2825static int
2826compiler_try_except(struct compiler *c, stmt_ty s)
2827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002829 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 body = compiler_new_block(c);
2832 except = compiler_new_block(c);
2833 orelse = compiler_new_block(c);
2834 end = compiler_new_block(c);
2835 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2836 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002837 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002839 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002841 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 ADDOP(c, POP_BLOCK);
2843 compiler_pop_fblock(c, EXCEPT, body);
2844 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002845 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 compiler_use_next_block(c, except);
2847 for (i = 0; i < n; i++) {
2848 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002849 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 if (!handler->v.ExceptHandler.type && i < n-1)
2851 return compiler_error(c, "default 'except:' must be last");
2852 c->u->u_lineno_set = 0;
2853 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002854 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 except = compiler_new_block(c);
2856 if (except == NULL)
2857 return 0;
2858 if (handler->v.ExceptHandler.type) {
2859 ADDOP(c, DUP_TOP);
2860 VISIT(c, expr, handler->v.ExceptHandler.type);
2861 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2862 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2863 }
2864 ADDOP(c, POP_TOP);
2865 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002866 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002867
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002868 cleanup_end = compiler_new_block(c);
2869 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002870 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002871 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002872 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002873
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002874 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2875 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002877 /*
2878 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002879 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002880 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002881 try:
2882 # body
2883 finally:
2884 name = None
2885 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002886 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002888 /* second try: */
2889 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2890 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002892 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002894 /* second # body */
2895 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2896 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 ADDOP(c, BEGIN_FINALLY);
2898 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002900 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002901 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002903 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002905 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002906 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002907 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002908 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002910 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002911 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002912 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 }
2914 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002915 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002917 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002918 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002919 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920
Guido van Rossumb940e112007-01-10 16:19:56 +00002921 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002922 ADDOP(c, POP_TOP);
2923 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002924 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002925 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002927 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002928 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 }
2930 ADDOP_JREL(c, JUMP_FORWARD, end);
2931 compiler_use_next_block(c, except);
2932 }
2933 ADDOP(c, END_FINALLY);
2934 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002935 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 compiler_use_next_block(c, end);
2937 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938}
2939
2940static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002941compiler_try(struct compiler *c, stmt_ty s) {
2942 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2943 return compiler_try_finally(c, s);
2944 else
2945 return compiler_try_except(c, s);
2946}
2947
2948
2949static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950compiler_import_as(struct compiler *c, identifier name, identifier asname)
2951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* The IMPORT_NAME opcode was already generated. This function
2953 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002956 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002958 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2959 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002960 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002961 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002962 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002964 while (1) {
2965 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002967 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002968 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002969 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002970 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002972 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002973 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002974 if (dot == -1) {
2975 break;
2976 }
2977 ADDOP(c, ROT_TWO);
2978 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002980 if (!compiler_nameop(c, asname, Store)) {
2981 return 0;
2982 }
2983 ADDOP(c, POP_TOP);
2984 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 }
2986 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987}
2988
2989static int
2990compiler_import(struct compiler *c, stmt_ty s)
2991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 /* The Import node stores a module name like a.b.c as a single
2993 string. This is convenient for all cases except
2994 import a.b.c as d
2995 where we need to parse that string to extract the individual
2996 module names.
2997 XXX Perhaps change the representation to make this case simpler?
2998 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002999 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 for (i = 0; i < n; i++) {
3002 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3003 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003005 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3006 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 if (alias->asname) {
3010 r = compiler_import_as(c, alias->name, alias->asname);
3011 if (!r)
3012 return r;
3013 }
3014 else {
3015 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003016 Py_ssize_t dot = PyUnicode_FindChar(
3017 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003018 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003020 if (tmp == NULL)
3021 return 0;
3022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003024 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 Py_DECREF(tmp);
3026 }
3027 if (!r)
3028 return r;
3029 }
3030 }
3031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032}
3033
3034static int
3035compiler_from_import(struct compiler *c, stmt_ty s)
3036{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003037 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003038 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 if (!empty_string) {
3042 empty_string = PyUnicode_FromString("");
3043 if (!empty_string)
3044 return 0;
3045 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003047 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003048
3049 names = PyTuple_New(n);
3050 if (!names)
3051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 /* build up the names */
3054 for (i = 0; i < n; i++) {
3055 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3056 Py_INCREF(alias->name);
3057 PyTuple_SET_ITEM(names, i, alias->name);
3058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003061 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 Py_DECREF(names);
3063 return compiler_error(c, "from __future__ imports must occur "
3064 "at the beginning of the file");
3065 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003066 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 if (s->v.ImportFrom.module) {
3069 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3070 }
3071 else {
3072 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3073 }
3074 for (i = 0; i < n; i++) {
3075 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3076 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003078 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 assert(n == 1);
3080 ADDOP(c, IMPORT_STAR);
3081 return 1;
3082 }
3083
3084 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3085 store_name = alias->name;
3086 if (alias->asname)
3087 store_name = alias->asname;
3088
3089 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 return 0;
3091 }
3092 }
3093 /* remove imported module */
3094 ADDOP(c, POP_TOP);
3095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096}
3097
3098static int
3099compiler_assert(struct compiler *c, stmt_ty s)
3100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 static PyObject *assertion_error = NULL;
3102 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103
Georg Brandl8334fd92010-12-04 10:26:46 +00003104 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 return 1;
3106 if (assertion_error == NULL) {
3107 assertion_error = PyUnicode_InternFromString("AssertionError");
3108 if (assertion_error == NULL)
3109 return 0;
3110 }
3111 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003112 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3113 {
3114 if (!compiler_warn(c, "assertion is always true, "
3115 "perhaps remove parentheses?"))
3116 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003117 return 0;
3118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 end = compiler_new_block(c);
3121 if (end == NULL)
3122 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003123 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3124 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3126 if (s->v.Assert.msg) {
3127 VISIT(c, expr, s->v.Assert.msg);
3128 ADDOP_I(c, CALL_FUNCTION, 1);
3129 }
3130 ADDOP_I(c, RAISE_VARARGS, 1);
3131 compiler_use_next_block(c, end);
3132 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133}
3134
3135static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003136compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3137{
3138 if (c->c_interactive && c->c_nestlevel <= 1) {
3139 VISIT(c, expr, value);
3140 ADDOP(c, PRINT_EXPR);
3141 return 1;
3142 }
3143
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003144 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003145 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003146 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003147 }
3148
3149 VISIT(c, expr, value);
3150 ADDOP(c, POP_TOP);
3151 return 1;
3152}
3153
3154static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155compiler_visit_stmt(struct compiler *c, stmt_ty s)
3156{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003157 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* Always assign a lineno to the next instruction for a stmt. */
3160 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003161 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 switch (s->kind) {
3165 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003166 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 case ClassDef_kind:
3168 return compiler_class(c, s);
3169 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003170 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 case Delete_kind:
3172 VISIT_SEQ(c, expr, s->v.Delete.targets)
3173 break;
3174 case Assign_kind:
3175 n = asdl_seq_LEN(s->v.Assign.targets);
3176 VISIT(c, expr, s->v.Assign.value);
3177 for (i = 0; i < n; i++) {
3178 if (i < n - 1)
3179 ADDOP(c, DUP_TOP);
3180 VISIT(c, expr,
3181 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3182 }
3183 break;
3184 case AugAssign_kind:
3185 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003186 case AnnAssign_kind:
3187 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 case For_kind:
3189 return compiler_for(c, s);
3190 case While_kind:
3191 return compiler_while(c, s);
3192 case If_kind:
3193 return compiler_if(c, s);
3194 case Raise_kind:
3195 n = 0;
3196 if (s->v.Raise.exc) {
3197 VISIT(c, expr, s->v.Raise.exc);
3198 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003199 if (s->v.Raise.cause) {
3200 VISIT(c, expr, s->v.Raise.cause);
3201 n++;
3202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003204 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003206 case Try_kind:
3207 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 case Assert_kind:
3209 return compiler_assert(c, s);
3210 case Import_kind:
3211 return compiler_import(c, s);
3212 case ImportFrom_kind:
3213 return compiler_from_import(c, s);
3214 case Global_kind:
3215 case Nonlocal_kind:
3216 break;
3217 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003218 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 case Pass_kind:
3220 break;
3221 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003222 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 case Continue_kind:
3224 return compiler_continue(c);
3225 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003226 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003227 case AsyncFunctionDef_kind:
3228 return compiler_function(c, s, 1);
3229 case AsyncWith_kind:
3230 return compiler_async_with(c, s, 0);
3231 case AsyncFor_kind:
3232 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 }
Yury Selivanov75445082015-05-11 22:57:16 -04003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236}
3237
3238static int
3239unaryop(unaryop_ty op)
3240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 switch (op) {
3242 case Invert:
3243 return UNARY_INVERT;
3244 case Not:
3245 return UNARY_NOT;
3246 case UAdd:
3247 return UNARY_POSITIVE;
3248 case USub:
3249 return UNARY_NEGATIVE;
3250 default:
3251 PyErr_Format(PyExc_SystemError,
3252 "unary op %d should not be possible", op);
3253 return 0;
3254 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255}
3256
3257static int
3258binop(struct compiler *c, operator_ty op)
3259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 switch (op) {
3261 case Add:
3262 return BINARY_ADD;
3263 case Sub:
3264 return BINARY_SUBTRACT;
3265 case Mult:
3266 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003267 case MatMult:
3268 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 case Div:
3270 return BINARY_TRUE_DIVIDE;
3271 case Mod:
3272 return BINARY_MODULO;
3273 case Pow:
3274 return BINARY_POWER;
3275 case LShift:
3276 return BINARY_LSHIFT;
3277 case RShift:
3278 return BINARY_RSHIFT;
3279 case BitOr:
3280 return BINARY_OR;
3281 case BitXor:
3282 return BINARY_XOR;
3283 case BitAnd:
3284 return BINARY_AND;
3285 case FloorDiv:
3286 return BINARY_FLOOR_DIVIDE;
3287 default:
3288 PyErr_Format(PyExc_SystemError,
3289 "binary op %d should not be possible", op);
3290 return 0;
3291 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292}
3293
3294static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295inplace_binop(struct compiler *c, operator_ty op)
3296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 switch (op) {
3298 case Add:
3299 return INPLACE_ADD;
3300 case Sub:
3301 return INPLACE_SUBTRACT;
3302 case Mult:
3303 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003304 case MatMult:
3305 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 case Div:
3307 return INPLACE_TRUE_DIVIDE;
3308 case Mod:
3309 return INPLACE_MODULO;
3310 case Pow:
3311 return INPLACE_POWER;
3312 case LShift:
3313 return INPLACE_LSHIFT;
3314 case RShift:
3315 return INPLACE_RSHIFT;
3316 case BitOr:
3317 return INPLACE_OR;
3318 case BitXor:
3319 return INPLACE_XOR;
3320 case BitAnd:
3321 return INPLACE_AND;
3322 case FloorDiv:
3323 return INPLACE_FLOOR_DIVIDE;
3324 default:
3325 PyErr_Format(PyExc_SystemError,
3326 "inplace binary op %d should not be possible", op);
3327 return 0;
3328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329}
3330
3331static int
3332compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3333{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003334 int op, scope;
3335 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 PyObject *dict = c->u->u_names;
3339 PyObject *mangled;
3340 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003341
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003342 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3343 !_PyUnicode_EqualToASCIIString(name, "True") &&
3344 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003345
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003346 mangled = _Py_Mangle(c->u->u_private, name);
3347 if (!mangled)
3348 return 0;
3349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 op = 0;
3351 optype = OP_NAME;
3352 scope = PyST_GetScope(c->u->u_ste, mangled);
3353 switch (scope) {
3354 case FREE:
3355 dict = c->u->u_freevars;
3356 optype = OP_DEREF;
3357 break;
3358 case CELL:
3359 dict = c->u->u_cellvars;
3360 optype = OP_DEREF;
3361 break;
3362 case LOCAL:
3363 if (c->u->u_ste->ste_type == FunctionBlock)
3364 optype = OP_FAST;
3365 break;
3366 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003367 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 optype = OP_GLOBAL;
3369 break;
3370 case GLOBAL_EXPLICIT:
3371 optype = OP_GLOBAL;
3372 break;
3373 default:
3374 /* scope can be 0 */
3375 break;
3376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 switch (optype) {
3382 case OP_DEREF:
3383 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003384 case Load:
3385 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3386 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 case Store: op = STORE_DEREF; break;
3388 case AugLoad:
3389 case AugStore:
3390 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003391 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Param:
3393 default:
3394 PyErr_SetString(PyExc_SystemError,
3395 "param invalid for deref variable");
3396 return 0;
3397 }
3398 break;
3399 case OP_FAST:
3400 switch (ctx) {
3401 case Load: op = LOAD_FAST; break;
3402 case Store: op = STORE_FAST; break;
3403 case Del: op = DELETE_FAST; break;
3404 case AugLoad:
3405 case AugStore:
3406 break;
3407 case Param:
3408 default:
3409 PyErr_SetString(PyExc_SystemError,
3410 "param invalid for local variable");
3411 return 0;
3412 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003413 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 return 1;
3415 case OP_GLOBAL:
3416 switch (ctx) {
3417 case Load: op = LOAD_GLOBAL; break;
3418 case Store: op = STORE_GLOBAL; break;
3419 case Del: op = DELETE_GLOBAL; break;
3420 case AugLoad:
3421 case AugStore:
3422 break;
3423 case Param:
3424 default:
3425 PyErr_SetString(PyExc_SystemError,
3426 "param invalid for global variable");
3427 return 0;
3428 }
3429 break;
3430 case OP_NAME:
3431 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003432 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 case Store: op = STORE_NAME; break;
3434 case Del: op = DELETE_NAME; break;
3435 case AugLoad:
3436 case AugStore:
3437 break;
3438 case Param:
3439 default:
3440 PyErr_SetString(PyExc_SystemError,
3441 "param invalid for name variable");
3442 return 0;
3443 }
3444 break;
3445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 assert(op);
3448 arg = compiler_add_o(c, dict, mangled);
3449 Py_DECREF(mangled);
3450 if (arg < 0)
3451 return 0;
3452 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453}
3454
3455static int
3456compiler_boolop(struct compiler *c, expr_ty e)
3457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003459 int jumpi;
3460 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 assert(e->kind == BoolOp_kind);
3464 if (e->v.BoolOp.op == And)
3465 jumpi = JUMP_IF_FALSE_OR_POP;
3466 else
3467 jumpi = JUMP_IF_TRUE_OR_POP;
3468 end = compiler_new_block(c);
3469 if (end == NULL)
3470 return 0;
3471 s = e->v.BoolOp.values;
3472 n = asdl_seq_LEN(s) - 1;
3473 assert(n >= 0);
3474 for (i = 0; i < n; ++i) {
3475 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3476 ADDOP_JABS(c, jumpi, end);
3477 }
3478 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3479 compiler_use_next_block(c, end);
3480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481}
3482
3483static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003484starunpack_helper(struct compiler *c, asdl_seq *elts,
3485 int single_op, int inner_op, int outer_op)
3486{
3487 Py_ssize_t n = asdl_seq_LEN(elts);
3488 Py_ssize_t i, nsubitems = 0, nseen = 0;
3489 for (i = 0; i < n; i++) {
3490 expr_ty elt = asdl_seq_GET(elts, i);
3491 if (elt->kind == Starred_kind) {
3492 if (nseen) {
3493 ADDOP_I(c, inner_op, nseen);
3494 nseen = 0;
3495 nsubitems++;
3496 }
3497 VISIT(c, expr, elt->v.Starred.value);
3498 nsubitems++;
3499 }
3500 else {
3501 VISIT(c, expr, elt);
3502 nseen++;
3503 }
3504 }
3505 if (nsubitems) {
3506 if (nseen) {
3507 ADDOP_I(c, inner_op, nseen);
3508 nsubitems++;
3509 }
3510 ADDOP_I(c, outer_op, nsubitems);
3511 }
3512 else
3513 ADDOP_I(c, single_op, nseen);
3514 return 1;
3515}
3516
3517static int
3518assignment_helper(struct compiler *c, asdl_seq *elts)
3519{
3520 Py_ssize_t n = asdl_seq_LEN(elts);
3521 Py_ssize_t i;
3522 int seen_star = 0;
3523 for (i = 0; i < n; i++) {
3524 expr_ty elt = asdl_seq_GET(elts, i);
3525 if (elt->kind == Starred_kind && !seen_star) {
3526 if ((i >= (1 << 8)) ||
3527 (n-i-1 >= (INT_MAX >> 8)))
3528 return compiler_error(c,
3529 "too many expressions in "
3530 "star-unpacking assignment");
3531 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3532 seen_star = 1;
3533 asdl_seq_SET(elts, i, elt->v.Starred.value);
3534 }
3535 else if (elt->kind == Starred_kind) {
3536 return compiler_error(c,
3537 "two starred expressions in assignment");
3538 }
3539 }
3540 if (!seen_star) {
3541 ADDOP_I(c, UNPACK_SEQUENCE, n);
3542 }
3543 VISIT_SEQ(c, expr, elts);
3544 return 1;
3545}
3546
3547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548compiler_list(struct compiler *c, expr_ty e)
3549{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003550 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003552 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003554 else if (e->v.List.ctx == Load) {
3555 return starunpack_helper(c, elts,
3556 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003558 else
3559 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561}
3562
3563static int
3564compiler_tuple(struct compiler *c, expr_ty e)
3565{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003566 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003568 return assignment_helper(c, elts);
3569 }
3570 else if (e->v.Tuple.ctx == Load) {
3571 return starunpack_helper(c, elts,
3572 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3573 }
3574 else
3575 VISIT_SEQ(c, expr, elts);
3576 return 1;
3577}
3578
3579static int
3580compiler_set(struct compiler *c, expr_ty e)
3581{
3582 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3583 BUILD_SET, BUILD_SET_UNPACK);
3584}
3585
3586static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003587are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3588{
3589 Py_ssize_t i;
3590 for (i = begin; i < end; i++) {
3591 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003592 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003593 return 0;
3594 }
3595 return 1;
3596}
3597
3598static int
3599compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3600{
3601 Py_ssize_t i, n = end - begin;
3602 PyObject *keys, *key;
3603 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3604 for (i = begin; i < end; i++) {
3605 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3606 }
3607 keys = PyTuple_New(n);
3608 if (keys == NULL) {
3609 return 0;
3610 }
3611 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003612 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003613 Py_INCREF(key);
3614 PyTuple_SET_ITEM(keys, i - begin, key);
3615 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003616 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003617 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3618 }
3619 else {
3620 for (i = begin; i < end; i++) {
3621 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3622 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3623 }
3624 ADDOP_I(c, BUILD_MAP, n);
3625 }
3626 return 1;
3627}
3628
3629static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003630compiler_dict(struct compiler *c, expr_ty e)
3631{
Victor Stinner976bb402016-03-23 11:36:19 +01003632 Py_ssize_t i, n, elements;
3633 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003634 int is_unpacking = 0;
3635 n = asdl_seq_LEN(e->v.Dict.values);
3636 containers = 0;
3637 elements = 0;
3638 for (i = 0; i < n; i++) {
3639 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3640 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003641 if (!compiler_subdict(c, e, i - elements, i))
3642 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003643 containers++;
3644 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003646 if (is_unpacking) {
3647 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3648 containers++;
3649 }
3650 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003651 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 }
3653 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003654 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003655 if (!compiler_subdict(c, e, n - elements, n))
3656 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003657 containers++;
3658 }
3659 /* If there is more than one dict, they need to be merged into a new
3660 * dict. If there is one dict and it's an unpacking, then it needs
3661 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003662 if (containers > 1 || is_unpacking) {
3663 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 }
3665 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666}
3667
3668static int
3669compiler_compare(struct compiler *c, expr_ty e)
3670{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003671 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003674 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3675 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3676 if (n == 0) {
3677 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3678 ADDOP_I(c, COMPARE_OP,
3679 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3680 }
3681 else {
3682 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (cleanup == NULL)
3684 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003685 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 VISIT(c, expr,
3687 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003688 ADDOP(c, DUP_TOP);
3689 ADDOP(c, ROT_THREE);
3690 ADDOP_I(c, COMPARE_OP,
3691 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3692 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3693 NEXT_BLOCK(c);
3694 }
3695 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3696 ADDOP_I(c, COMPARE_OP,
3697 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 basicblock *end = compiler_new_block(c);
3699 if (end == NULL)
3700 return 0;
3701 ADDOP_JREL(c, JUMP_FORWARD, end);
3702 compiler_use_next_block(c, cleanup);
3703 ADDOP(c, ROT_TWO);
3704 ADDOP(c, POP_TOP);
3705 compiler_use_next_block(c, end);
3706 }
3707 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708}
3709
3710static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003711maybe_optimize_method_call(struct compiler *c, expr_ty e)
3712{
3713 Py_ssize_t argsl, i;
3714 expr_ty meth = e->v.Call.func;
3715 asdl_seq *args = e->v.Call.args;
3716
3717 /* Check that the call node is an attribute access, and that
3718 the call doesn't have keyword parameters. */
3719 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3720 asdl_seq_LEN(e->v.Call.keywords))
3721 return -1;
3722
3723 /* Check that there are no *varargs types of arguments. */
3724 argsl = asdl_seq_LEN(args);
3725 for (i = 0; i < argsl; i++) {
3726 expr_ty elt = asdl_seq_GET(args, i);
3727 if (elt->kind == Starred_kind) {
3728 return -1;
3729 }
3730 }
3731
3732 /* Alright, we can optimize the code. */
3733 VISIT(c, expr, meth->v.Attribute.value);
3734 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3735 VISIT_SEQ(c, expr, e->v.Call.args);
3736 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3737 return 1;
3738}
3739
3740static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741compiler_call(struct compiler *c, expr_ty e)
3742{
Yury Selivanovf2392132016-12-13 19:03:51 -05003743 if (maybe_optimize_method_call(c, e) > 0)
3744 return 1;
3745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 VISIT(c, expr, e->v.Call.func);
3747 return compiler_call_helper(c, 0,
3748 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003750}
3751
Eric V. Smith235a6f02015-09-19 14:51:32 -04003752static int
3753compiler_joined_str(struct compiler *c, expr_ty e)
3754{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003755 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003756 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3757 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003758 return 1;
3759}
3760
Eric V. Smitha78c7952015-11-03 12:45:05 -05003761/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003762static int
3763compiler_formatted_value(struct compiler *c, expr_ty e)
3764{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003765 /* Our oparg encodes 2 pieces of information: the conversion
3766 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003767
Eric V. Smitha78c7952015-11-03 12:45:05 -05003768 Convert the conversion char to 2 bits:
3769 None: 000 0x0 FVC_NONE
3770 !s : 001 0x1 FVC_STR
3771 !r : 010 0x2 FVC_REPR
3772 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003773
Eric V. Smitha78c7952015-11-03 12:45:05 -05003774 next bit is whether or not we have a format spec:
3775 yes : 100 0x4
3776 no : 000 0x0
3777 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003778
Eric V. Smitha78c7952015-11-03 12:45:05 -05003779 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003780
Eric V. Smitha78c7952015-11-03 12:45:05 -05003781 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003782 VISIT(c, expr, e->v.FormattedValue.value);
3783
Eric V. Smitha78c7952015-11-03 12:45:05 -05003784 switch (e->v.FormattedValue.conversion) {
3785 case 's': oparg = FVC_STR; break;
3786 case 'r': oparg = FVC_REPR; break;
3787 case 'a': oparg = FVC_ASCII; break;
3788 case -1: oparg = FVC_NONE; break;
3789 default:
3790 PyErr_SetString(PyExc_SystemError,
3791 "Unrecognized conversion character");
3792 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003793 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003794 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003795 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003796 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003797 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003798 }
3799
Eric V. Smitha78c7952015-11-03 12:45:05 -05003800 /* And push our opcode and oparg */
3801 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003802 return 1;
3803}
3804
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003805static int
3806compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3807{
3808 Py_ssize_t i, n = end - begin;
3809 keyword_ty kw;
3810 PyObject *keys, *key;
3811 assert(n > 0);
3812 if (n > 1) {
3813 for (i = begin; i < end; i++) {
3814 kw = asdl_seq_GET(keywords, i);
3815 VISIT(c, expr, kw->value);
3816 }
3817 keys = PyTuple_New(n);
3818 if (keys == NULL) {
3819 return 0;
3820 }
3821 for (i = begin; i < end; i++) {
3822 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3823 Py_INCREF(key);
3824 PyTuple_SET_ITEM(keys, i - begin, key);
3825 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003826 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003827 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3828 }
3829 else {
3830 /* a for loop only executes once */
3831 for (i = begin; i < end; i++) {
3832 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003833 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003834 VISIT(c, expr, kw->value);
3835 }
3836 ADDOP_I(c, BUILD_MAP, n);
3837 }
3838 return 1;
3839}
3840
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003841/* shared code between compiler_call and compiler_class */
3842static int
3843compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003844 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003845 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003846 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003847{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003848 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003849 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003850
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003851 /* the number of tuples and dictionaries on the stack */
3852 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3853
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003854 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003855 nkwelts = asdl_seq_LEN(keywords);
3856
3857 for (i = 0; i < nkwelts; i++) {
3858 keyword_ty kw = asdl_seq_GET(keywords, i);
3859 if (kw->arg == NULL) {
3860 mustdictunpack = 1;
3861 break;
3862 }
3863 }
3864
3865 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003866 for (i = 0; i < nelts; i++) {
3867 expr_ty elt = asdl_seq_GET(args, i);
3868 if (elt->kind == Starred_kind) {
3869 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003870 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871 if (nseen) {
3872 ADDOP_I(c, BUILD_TUPLE, nseen);
3873 nseen = 0;
3874 nsubargs++;
3875 }
3876 VISIT(c, expr, elt->v.Starred.value);
3877 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 }
3879 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003881 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003882 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003884
3885 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003886 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003887 if (nseen) {
3888 /* Pack up any trailing positional arguments. */
3889 ADDOP_I(c, BUILD_TUPLE, nseen);
3890 nsubargs++;
3891 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003892 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003893 /* If we ended up with more than one stararg, we need
3894 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003895 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003896 }
3897 else if (nsubargs == 0) {
3898 ADDOP_I(c, BUILD_TUPLE, 0);
3899 }
3900 nseen = 0; /* the number of keyword arguments on the stack following */
3901 for (i = 0; i < nkwelts; i++) {
3902 keyword_ty kw = asdl_seq_GET(keywords, i);
3903 if (kw->arg == NULL) {
3904 /* A keyword argument unpacking. */
3905 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003906 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3907 return 0;
3908 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003909 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003910 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003911 VISIT(c, expr, kw->value);
3912 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003913 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003914 else {
3915 nseen++;
3916 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003917 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003918 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003919 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003920 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003921 return 0;
3922 nsubkwargs++;
3923 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003924 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003925 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003926 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003927 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003928 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3929 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003931 else if (nkwelts) {
3932 PyObject *names;
3933 VISIT_SEQ(c, keyword, keywords);
3934 names = PyTuple_New(nkwelts);
3935 if (names == NULL) {
3936 return 0;
3937 }
3938 for (i = 0; i < nkwelts; i++) {
3939 keyword_ty kw = asdl_seq_GET(keywords, i);
3940 Py_INCREF(kw->arg);
3941 PyTuple_SET_ITEM(names, i, kw->arg);
3942 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003943 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003944 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3945 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003947 else {
3948 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3949 return 1;
3950 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951}
3952
Nick Coghlan650f0d02007-04-15 12:05:43 +00003953
3954/* List and set comprehensions and generator expressions work by creating a
3955 nested function to perform the actual iteration. This means that the
3956 iteration variables don't leak into the current scope.
3957 The defined function is called immediately following its definition, with the
3958 result of that call being the result of the expression.
3959 The LC/SC version returns the populated container, while the GE version is
3960 flagged in symtable.c as a generator, so it returns the generator object
3961 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003962
3963 Possible cleanups:
3964 - iterate over the generator sequence instead of using recursion
3965*/
3966
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003968static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969compiler_comprehension_generator(struct compiler *c,
3970 asdl_seq *generators, int gen_index,
3971 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003973 comprehension_ty gen;
3974 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3975 if (gen->is_async) {
3976 return compiler_async_comprehension_generator(
3977 c, generators, gen_index, elt, val, type);
3978 } else {
3979 return compiler_sync_comprehension_generator(
3980 c, generators, gen_index, elt, val, type);
3981 }
3982}
3983
3984static int
3985compiler_sync_comprehension_generator(struct compiler *c,
3986 asdl_seq *generators, int gen_index,
3987 expr_ty elt, expr_ty val, int type)
3988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* generate code for the iterator, then each of the ifs,
3990 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 comprehension_ty gen;
3993 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003994 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 start = compiler_new_block(c);
3997 skip = compiler_new_block(c);
3998 if_cleanup = compiler_new_block(c);
3999 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4002 anchor == NULL)
4003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 if (gen_index == 0) {
4008 /* Receive outermost iter as an implicit argument */
4009 c->u->u_argcount = 1;
4010 ADDOP_I(c, LOAD_FAST, 0);
4011 }
4012 else {
4013 /* Sub-iter - calculate on the fly */
4014 VISIT(c, expr, gen->iter);
4015 ADDOP(c, GET_ITER);
4016 }
4017 compiler_use_next_block(c, start);
4018 ADDOP_JREL(c, FOR_ITER, anchor);
4019 NEXT_BLOCK(c);
4020 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 /* XXX this needs to be cleaned up...a lot! */
4023 n = asdl_seq_LEN(gen->ifs);
4024 for (i = 0; i < n; i++) {
4025 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004026 if (!compiler_jump_if(c, e, if_cleanup, 0))
4027 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 NEXT_BLOCK(c);
4029 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 if (++gen_index < asdl_seq_LEN(generators))
4032 if (!compiler_comprehension_generator(c,
4033 generators, gen_index,
4034 elt, val, type))
4035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 /* only append after the last for generator */
4038 if (gen_index >= asdl_seq_LEN(generators)) {
4039 /* comprehension specific code */
4040 switch (type) {
4041 case COMP_GENEXP:
4042 VISIT(c, expr, elt);
4043 ADDOP(c, YIELD_VALUE);
4044 ADDOP(c, POP_TOP);
4045 break;
4046 case COMP_LISTCOMP:
4047 VISIT(c, expr, elt);
4048 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4049 break;
4050 case COMP_SETCOMP:
4051 VISIT(c, expr, elt);
4052 ADDOP_I(c, SET_ADD, gen_index + 1);
4053 break;
4054 case COMP_DICTCOMP:
4055 /* With 'd[k] = v', v is evaluated before k, so we do
4056 the same. */
4057 VISIT(c, expr, val);
4058 VISIT(c, expr, elt);
4059 ADDOP_I(c, MAP_ADD, gen_index + 1);
4060 break;
4061 default:
4062 return 0;
4063 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 compiler_use_next_block(c, skip);
4066 }
4067 compiler_use_next_block(c, if_cleanup);
4068 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4069 compiler_use_next_block(c, anchor);
4070
4071 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072}
4073
4074static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004075compiler_async_comprehension_generator(struct compiler *c,
4076 asdl_seq *generators, int gen_index,
4077 expr_ty elt, expr_ty val, int type)
4078{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004079 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004080 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004081 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004082 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004083 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004084 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004085
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004086 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004087 return 0;
4088 }
4089
4090 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4091
4092 if (gen_index == 0) {
4093 /* Receive outermost iter as an implicit argument */
4094 c->u->u_argcount = 1;
4095 ADDOP_I(c, LOAD_FAST, 0);
4096 }
4097 else {
4098 /* Sub-iter - calculate on the fly */
4099 VISIT(c, expr, gen->iter);
4100 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004101 }
4102
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004103 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004104
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004105 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004106 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004107 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004108 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004109 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004110 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004111
4112 n = asdl_seq_LEN(gen->ifs);
4113 for (i = 0; i < n; i++) {
4114 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004115 if (!compiler_jump_if(c, e, if_cleanup, 0))
4116 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004117 NEXT_BLOCK(c);
4118 }
4119
4120 if (++gen_index < asdl_seq_LEN(generators))
4121 if (!compiler_comprehension_generator(c,
4122 generators, gen_index,
4123 elt, val, type))
4124 return 0;
4125
4126 /* only append after the last for generator */
4127 if (gen_index >= asdl_seq_LEN(generators)) {
4128 /* comprehension specific code */
4129 switch (type) {
4130 case COMP_GENEXP:
4131 VISIT(c, expr, elt);
4132 ADDOP(c, YIELD_VALUE);
4133 ADDOP(c, POP_TOP);
4134 break;
4135 case COMP_LISTCOMP:
4136 VISIT(c, expr, elt);
4137 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4138 break;
4139 case COMP_SETCOMP:
4140 VISIT(c, expr, elt);
4141 ADDOP_I(c, SET_ADD, gen_index + 1);
4142 break;
4143 case COMP_DICTCOMP:
4144 /* With 'd[k] = v', v is evaluated before k, so we do
4145 the same. */
4146 VISIT(c, expr, val);
4147 VISIT(c, expr, elt);
4148 ADDOP_I(c, MAP_ADD, gen_index + 1);
4149 break;
4150 default:
4151 return 0;
4152 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004153 }
4154 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004155 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4156
4157 compiler_use_next_block(c, except);
4158 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004159
4160 return 1;
4161}
4162
4163static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004164compiler_comprehension(struct compiler *c, expr_ty e, int type,
4165 identifier name, asdl_seq *generators, expr_ty elt,
4166 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004169 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004170 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004171 int is_async_function = c->u->u_ste->ste_coroutine;
4172 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004173
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004174 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004175
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004176 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4177 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004178 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004180 }
4181
4182 is_async_generator = c->u->u_ste->ste_coroutine;
4183
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004184 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004185 compiler_error(c, "asynchronous comprehension outside of "
4186 "an asynchronous function");
4187 goto error_in_scope;
4188 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (type != COMP_GENEXP) {
4191 int op;
4192 switch (type) {
4193 case COMP_LISTCOMP:
4194 op = BUILD_LIST;
4195 break;
4196 case COMP_SETCOMP:
4197 op = BUILD_SET;
4198 break;
4199 case COMP_DICTCOMP:
4200 op = BUILD_MAP;
4201 break;
4202 default:
4203 PyErr_Format(PyExc_SystemError,
4204 "unknown comprehension type %d", type);
4205 goto error_in_scope;
4206 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 ADDOP_I(c, op, 0);
4209 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 if (!compiler_comprehension_generator(c, generators, 0, elt,
4212 val, type))
4213 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 if (type != COMP_GENEXP) {
4216 ADDOP(c, RETURN_VALUE);
4217 }
4218
4219 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004220 qualname = c->u->u_qualname;
4221 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004223 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 goto error;
4225
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004226 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004228 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 Py_DECREF(co);
4230
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004231 VISIT(c, expr, outermost->iter);
4232
4233 if (outermost->is_async) {
4234 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004235 } else {
4236 ADDOP(c, GET_ITER);
4237 }
4238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004240
4241 if (is_async_generator && type != COMP_GENEXP) {
4242 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004243 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004244 ADDOP(c, YIELD_FROM);
4245 }
4246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004248error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004250error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004251 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 Py_XDECREF(co);
4253 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004254}
4255
4256static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257compiler_genexp(struct compiler *c, expr_ty e)
4258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 static identifier name;
4260 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004261 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (!name)
4263 return 0;
4264 }
4265 assert(e->kind == GeneratorExp_kind);
4266 return compiler_comprehension(c, e, COMP_GENEXP, name,
4267 e->v.GeneratorExp.generators,
4268 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269}
4270
4271static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004272compiler_listcomp(struct compiler *c, expr_ty e)
4273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 static identifier name;
4275 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004276 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 if (!name)
4278 return 0;
4279 }
4280 assert(e->kind == ListComp_kind);
4281 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4282 e->v.ListComp.generators,
4283 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004284}
4285
4286static int
4287compiler_setcomp(struct compiler *c, expr_ty e)
4288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 static identifier name;
4290 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004291 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (!name)
4293 return 0;
4294 }
4295 assert(e->kind == SetComp_kind);
4296 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4297 e->v.SetComp.generators,
4298 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004299}
4300
4301
4302static int
4303compiler_dictcomp(struct compiler *c, expr_ty e)
4304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 static identifier name;
4306 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004307 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 if (!name)
4309 return 0;
4310 }
4311 assert(e->kind == DictComp_kind);
4312 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4313 e->v.DictComp.generators,
4314 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004315}
4316
4317
4318static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004319compiler_visit_keyword(struct compiler *c, keyword_ty k)
4320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 VISIT(c, expr, k->value);
4322 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323}
4324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326 whether they are true or false.
4327
4328 Return values: 1 for true, 0 for false, -1 for non-constant.
4329 */
4330
4331static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004332expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004333{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004334 if (e->kind == Constant_kind) {
4335 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004336 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004337 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004338}
4339
Yury Selivanov75445082015-05-11 22:57:16 -04004340
4341/*
4342 Implements the async with statement.
4343
4344 The semantics outlined in that PEP are as follows:
4345
4346 async with EXPR as VAR:
4347 BLOCK
4348
4349 It is implemented roughly as:
4350
4351 context = EXPR
4352 exit = context.__aexit__ # not calling it
4353 value = await context.__aenter__()
4354 try:
4355 VAR = value # if VAR present in the syntax
4356 BLOCK
4357 finally:
4358 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004359 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004360 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004361 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004362 if not (await exit(*exc)):
4363 raise
4364 */
4365static int
4366compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4367{
4368 basicblock *block, *finally;
4369 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4370
4371 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004372 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4373 return compiler_error(c, "'async with' outside async function");
4374 }
Yury Selivanov75445082015-05-11 22:57:16 -04004375
4376 block = compiler_new_block(c);
4377 finally = compiler_new_block(c);
4378 if (!block || !finally)
4379 return 0;
4380
4381 /* Evaluate EXPR */
4382 VISIT(c, expr, item->context_expr);
4383
4384 ADDOP(c, BEFORE_ASYNC_WITH);
4385 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004386 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004387 ADDOP(c, YIELD_FROM);
4388
4389 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4390
4391 /* SETUP_ASYNC_WITH pushes a finally block. */
4392 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004393 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004394 return 0;
4395 }
4396
4397 if (item->optional_vars) {
4398 VISIT(c, expr, item->optional_vars);
4399 }
4400 else {
4401 /* Discard result from context.__aenter__() */
4402 ADDOP(c, POP_TOP);
4403 }
4404
4405 pos++;
4406 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4407 /* BLOCK code */
4408 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4409 else if (!compiler_async_with(c, s, pos))
4410 return 0;
4411
4412 /* End of try block; start the finally block */
4413 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004414 ADDOP(c, BEGIN_FINALLY);
4415 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004416
Yury Selivanov75445082015-05-11 22:57:16 -04004417 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004418 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004419 return 0;
4420
4421 /* Finally block starts; context.__exit__ is on the stack under
4422 the exception or return information. Just issue our magic
4423 opcode. */
4424 ADDOP(c, WITH_CLEANUP_START);
4425
4426 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004427 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004428 ADDOP(c, YIELD_FROM);
4429
4430 ADDOP(c, WITH_CLEANUP_FINISH);
4431
4432 /* Finally block ends. */
4433 ADDOP(c, END_FINALLY);
4434 compiler_pop_fblock(c, FINALLY_END, finally);
4435 return 1;
4436}
4437
4438
Guido van Rossumc2e20742006-02-27 22:32:47 +00004439/*
4440 Implements the with statement from PEP 343.
4441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004443
4444 with EXPR as VAR:
4445 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446
Guido van Rossumc2e20742006-02-27 22:32:47 +00004447 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448
Thomas Wouters477c8d52006-05-27 19:21:47 +00004449 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004450 exit = context.__exit__ # not calling it
4451 value = context.__enter__()
4452 try:
4453 VAR = value # if VAR present in the syntax
4454 BLOCK
4455 finally:
4456 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004457 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004458 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004459 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004460 exit(*exc)
4461 */
4462static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004463compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004464{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004465 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004466 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004467
4468 assert(s->kind == With_kind);
4469
Guido van Rossumc2e20742006-02-27 22:32:47 +00004470 block = compiler_new_block(c);
4471 finally = compiler_new_block(c);
4472 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004473 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004474
Thomas Wouters477c8d52006-05-27 19:21:47 +00004475 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004476 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004477 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004478
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004479 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004480 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004481 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004482 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004483 }
4484
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004485 if (item->optional_vars) {
4486 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004487 }
4488 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004490 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004491 }
4492
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004493 pos++;
4494 if (pos == asdl_seq_LEN(s->v.With.items))
4495 /* BLOCK code */
4496 VISIT_SEQ(c, stmt, s->v.With.body)
4497 else if (!compiler_with(c, s, pos))
4498 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004499
4500 /* End of try block; start the finally block */
4501 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004502 ADDOP(c, BEGIN_FINALLY);
4503 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004504
Guido van Rossumc2e20742006-02-27 22:32:47 +00004505 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004506 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004507 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004508
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004509 /* Finally block starts; context.__exit__ is on the stack under
4510 the exception or return information. Just issue our magic
4511 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004512 ADDOP(c, WITH_CLEANUP_START);
4513 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004514
4515 /* Finally block ends. */
4516 ADDOP(c, END_FINALLY);
4517 compiler_pop_fblock(c, FINALLY_END, finally);
4518 return 1;
4519}
4520
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004521static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004522compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 switch (e->kind) {
4525 case BoolOp_kind:
4526 return compiler_boolop(c, e);
4527 case BinOp_kind:
4528 VISIT(c, expr, e->v.BinOp.left);
4529 VISIT(c, expr, e->v.BinOp.right);
4530 ADDOP(c, binop(c, e->v.BinOp.op));
4531 break;
4532 case UnaryOp_kind:
4533 VISIT(c, expr, e->v.UnaryOp.operand);
4534 ADDOP(c, unaryop(e->v.UnaryOp.op));
4535 break;
4536 case Lambda_kind:
4537 return compiler_lambda(c, e);
4538 case IfExp_kind:
4539 return compiler_ifexp(c, e);
4540 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004541 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004543 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 case GeneratorExp_kind:
4545 return compiler_genexp(c, e);
4546 case ListComp_kind:
4547 return compiler_listcomp(c, e);
4548 case SetComp_kind:
4549 return compiler_setcomp(c, e);
4550 case DictComp_kind:
4551 return compiler_dictcomp(c, e);
4552 case Yield_kind:
4553 if (c->u->u_ste->ste_type != FunctionBlock)
4554 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004555 if (e->v.Yield.value) {
4556 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 }
4558 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004559 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004561 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004563 case YieldFrom_kind:
4564 if (c->u->u_ste->ste_type != FunctionBlock)
4565 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004566
4567 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4568 return compiler_error(c, "'yield from' inside async function");
4569
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004570 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004571 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004572 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004573 ADDOP(c, YIELD_FROM);
4574 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004575 case Await_kind:
4576 if (c->u->u_ste->ste_type != FunctionBlock)
4577 return compiler_error(c, "'await' outside function");
4578
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4580 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004581 return compiler_error(c, "'await' outside async function");
4582
4583 VISIT(c, expr, e->v.Await.value);
4584 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004585 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004586 ADDOP(c, YIELD_FROM);
4587 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 case Compare_kind:
4589 return compiler_compare(c, e);
4590 case Call_kind:
4591 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004592 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004593 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004594 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004595 case JoinedStr_kind:
4596 return compiler_joined_str(c, e);
4597 case FormattedValue_kind:
4598 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 /* The following exprs can be assignment targets. */
4600 case Attribute_kind:
4601 if (e->v.Attribute.ctx != AugStore)
4602 VISIT(c, expr, e->v.Attribute.value);
4603 switch (e->v.Attribute.ctx) {
4604 case AugLoad:
4605 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004606 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 case Load:
4608 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4609 break;
4610 case AugStore:
4611 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004612 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 case Store:
4614 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4615 break;
4616 case Del:
4617 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4618 break;
4619 case Param:
4620 default:
4621 PyErr_SetString(PyExc_SystemError,
4622 "param invalid in attribute expression");
4623 return 0;
4624 }
4625 break;
4626 case Subscript_kind:
4627 switch (e->v.Subscript.ctx) {
4628 case AugLoad:
4629 VISIT(c, expr, e->v.Subscript.value);
4630 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4631 break;
4632 case Load:
4633 VISIT(c, expr, e->v.Subscript.value);
4634 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4635 break;
4636 case AugStore:
4637 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4638 break;
4639 case Store:
4640 VISIT(c, expr, e->v.Subscript.value);
4641 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4642 break;
4643 case Del:
4644 VISIT(c, expr, e->v.Subscript.value);
4645 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4646 break;
4647 case Param:
4648 default:
4649 PyErr_SetString(PyExc_SystemError,
4650 "param invalid in subscript expression");
4651 return 0;
4652 }
4653 break;
4654 case Starred_kind:
4655 switch (e->v.Starred.ctx) {
4656 case Store:
4657 /* In all legitimate cases, the Starred node was already replaced
4658 * by compiler_list/compiler_tuple. XXX: is that okay? */
4659 return compiler_error(c,
4660 "starred assignment target must be in a list or tuple");
4661 default:
4662 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004663 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 }
4665 break;
4666 case Name_kind:
4667 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4668 /* child nodes of List and Tuple will have expr_context set */
4669 case List_kind:
4670 return compiler_list(c, e);
4671 case Tuple_kind:
4672 return compiler_tuple(c, e);
4673 }
4674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004675}
4676
4677static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004678compiler_visit_expr(struct compiler *c, expr_ty e)
4679{
4680 /* If expr e has a different line number than the last expr/stmt,
4681 set a new line number for the next instruction.
4682 */
4683 int old_lineno = c->u->u_lineno;
4684 int old_col_offset = c->u->u_col_offset;
4685 if (e->lineno != c->u->u_lineno) {
4686 c->u->u_lineno = e->lineno;
4687 c->u->u_lineno_set = 0;
4688 }
4689 /* Updating the column offset is always harmless. */
4690 c->u->u_col_offset = e->col_offset;
4691
4692 int res = compiler_visit_expr1(c, e);
4693
4694 if (old_lineno != c->u->u_lineno) {
4695 c->u->u_lineno = old_lineno;
4696 c->u->u_lineno_set = 0;
4697 }
4698 c->u->u_col_offset = old_col_offset;
4699 return res;
4700}
4701
4702static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004703compiler_augassign(struct compiler *c, stmt_ty s)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 expr_ty e = s->v.AugAssign.target;
4706 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 switch (e->kind) {
4711 case Attribute_kind:
4712 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4713 AugLoad, e->lineno, e->col_offset, c->c_arena);
4714 if (auge == NULL)
4715 return 0;
4716 VISIT(c, expr, auge);
4717 VISIT(c, expr, s->v.AugAssign.value);
4718 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4719 auge->v.Attribute.ctx = AugStore;
4720 VISIT(c, expr, auge);
4721 break;
4722 case Subscript_kind:
4723 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4724 AugLoad, e->lineno, e->col_offset, c->c_arena);
4725 if (auge == NULL)
4726 return 0;
4727 VISIT(c, expr, auge);
4728 VISIT(c, expr, s->v.AugAssign.value);
4729 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4730 auge->v.Subscript.ctx = AugStore;
4731 VISIT(c, expr, auge);
4732 break;
4733 case Name_kind:
4734 if (!compiler_nameop(c, e->v.Name.id, Load))
4735 return 0;
4736 VISIT(c, expr, s->v.AugAssign.value);
4737 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4738 return compiler_nameop(c, e->v.Name.id, Store);
4739 default:
4740 PyErr_Format(PyExc_SystemError,
4741 "invalid node type (%d) for augmented assignment",
4742 e->kind);
4743 return 0;
4744 }
4745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004746}
4747
4748static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004749check_ann_expr(struct compiler *c, expr_ty e)
4750{
4751 VISIT(c, expr, e);
4752 ADDOP(c, POP_TOP);
4753 return 1;
4754}
4755
4756static int
4757check_annotation(struct compiler *c, stmt_ty s)
4758{
4759 /* Annotations are only evaluated in a module or class. */
4760 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4761 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4762 return check_ann_expr(c, s->v.AnnAssign.annotation);
4763 }
4764 return 1;
4765}
4766
4767static int
4768check_ann_slice(struct compiler *c, slice_ty sl)
4769{
4770 switch(sl->kind) {
4771 case Index_kind:
4772 return check_ann_expr(c, sl->v.Index.value);
4773 case Slice_kind:
4774 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4775 return 0;
4776 }
4777 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4778 return 0;
4779 }
4780 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4781 return 0;
4782 }
4783 break;
4784 default:
4785 PyErr_SetString(PyExc_SystemError,
4786 "unexpected slice kind");
4787 return 0;
4788 }
4789 return 1;
4790}
4791
4792static int
4793check_ann_subscr(struct compiler *c, slice_ty sl)
4794{
4795 /* We check that everything in a subscript is defined at runtime. */
4796 Py_ssize_t i, n;
4797
4798 switch (sl->kind) {
4799 case Index_kind:
4800 case Slice_kind:
4801 if (!check_ann_slice(c, sl)) {
4802 return 0;
4803 }
4804 break;
4805 case ExtSlice_kind:
4806 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4807 for (i = 0; i < n; i++) {
4808 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4809 switch (subsl->kind) {
4810 case Index_kind:
4811 case Slice_kind:
4812 if (!check_ann_slice(c, subsl)) {
4813 return 0;
4814 }
4815 break;
4816 case ExtSlice_kind:
4817 default:
4818 PyErr_SetString(PyExc_SystemError,
4819 "extended slice invalid in nested slice");
4820 return 0;
4821 }
4822 }
4823 break;
4824 default:
4825 PyErr_Format(PyExc_SystemError,
4826 "invalid subscript kind %d", sl->kind);
4827 return 0;
4828 }
4829 return 1;
4830}
4831
4832static int
4833compiler_annassign(struct compiler *c, stmt_ty s)
4834{
4835 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004836 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004837
4838 assert(s->kind == AnnAssign_kind);
4839
4840 /* We perform the actual assignment first. */
4841 if (s->v.AnnAssign.value) {
4842 VISIT(c, expr, s->v.AnnAssign.value);
4843 VISIT(c, expr, targ);
4844 }
4845 switch (targ->kind) {
4846 case Name_kind:
4847 /* If we have a simple name in a module or class, store annotation. */
4848 if (s->v.AnnAssign.simple &&
4849 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4850 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004851 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4852 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4853 }
4854 else {
4855 VISIT(c, expr, s->v.AnnAssign.annotation);
4856 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004857 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004858 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004859 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004860 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004861 }
4862 break;
4863 case Attribute_kind:
4864 if (!s->v.AnnAssign.value &&
4865 !check_ann_expr(c, targ->v.Attribute.value)) {
4866 return 0;
4867 }
4868 break;
4869 case Subscript_kind:
4870 if (!s->v.AnnAssign.value &&
4871 (!check_ann_expr(c, targ->v.Subscript.value) ||
4872 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4873 return 0;
4874 }
4875 break;
4876 default:
4877 PyErr_Format(PyExc_SystemError,
4878 "invalid node type (%d) for annotated assignment",
4879 targ->kind);
4880 return 0;
4881 }
4882 /* Annotation is evaluated last. */
4883 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4884 return 0;
4885 }
4886 return 1;
4887}
4888
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004889/* Raises a SyntaxError and returns 0.
4890 If something goes wrong, a different exception may be raised.
4891*/
4892
4893static int
4894compiler_error(struct compiler *c, const char *errstr)
4895{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004896 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004898
Victor Stinner14e461d2013-08-26 22:28:21 +02004899 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 if (!loc) {
4901 Py_INCREF(Py_None);
4902 loc = Py_None;
4903 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004904 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004905 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 if (!u)
4907 goto exit;
4908 v = Py_BuildValue("(zO)", errstr, u);
4909 if (!v)
4910 goto exit;
4911 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004912 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 Py_DECREF(loc);
4914 Py_XDECREF(u);
4915 Py_XDECREF(v);
4916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004917}
4918
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004919/* Emits a SyntaxWarning and returns 1 on success.
4920 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4921 and returns 0.
4922*/
4923static int
4924compiler_warn(struct compiler *c, const char *errstr)
4925{
4926 PyObject *msg = PyUnicode_FromString(errstr);
4927 if (msg == NULL) {
4928 return 0;
4929 }
4930 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4931 c->u->u_lineno, NULL, NULL) < 0)
4932 {
4933 Py_DECREF(msg);
4934 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4935 PyErr_Clear();
4936 return compiler_error(c, errstr);
4937 }
4938 return 0;
4939 }
4940 Py_DECREF(msg);
4941 return 1;
4942}
4943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945compiler_handle_subscr(struct compiler *c, const char *kind,
4946 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 /* XXX this code is duplicated */
4951 switch (ctx) {
4952 case AugLoad: /* fall through to Load */
4953 case Load: op = BINARY_SUBSCR; break;
4954 case AugStore:/* fall through to Store */
4955 case Store: op = STORE_SUBSCR; break;
4956 case Del: op = DELETE_SUBSCR; break;
4957 case Param:
4958 PyErr_Format(PyExc_SystemError,
4959 "invalid %s kind %d in subscript\n",
4960 kind, ctx);
4961 return 0;
4962 }
4963 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004964 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 }
4966 else if (ctx == AugStore) {
4967 ADDOP(c, ROT_THREE);
4968 }
4969 ADDOP(c, op);
4970 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004971}
4972
4973static int
4974compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 int n = 2;
4977 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 /* only handles the cases where BUILD_SLICE is emitted */
4980 if (s->v.Slice.lower) {
4981 VISIT(c, expr, s->v.Slice.lower);
4982 }
4983 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004984 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 if (s->v.Slice.upper) {
4988 VISIT(c, expr, s->v.Slice.upper);
4989 }
4990 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004991 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 }
4993
4994 if (s->v.Slice.step) {
4995 n++;
4996 VISIT(c, expr, s->v.Slice.step);
4997 }
4998 ADDOP_I(c, BUILD_SLICE, n);
4999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000}
5001
5002static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5004 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 switch (s->kind) {
5007 case Slice_kind:
5008 return compiler_slice(c, s, ctx);
5009 case Index_kind:
5010 VISIT(c, expr, s->v.Index.value);
5011 break;
5012 case ExtSlice_kind:
5013 default:
5014 PyErr_SetString(PyExc_SystemError,
5015 "extended slice invalid in nested slice");
5016 return 0;
5017 }
5018 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005019}
5020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005021static int
5022compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5023{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005024 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 switch (s->kind) {
5026 case Index_kind:
5027 kindname = "index";
5028 if (ctx != AugStore) {
5029 VISIT(c, expr, s->v.Index.value);
5030 }
5031 break;
5032 case Slice_kind:
5033 kindname = "slice";
5034 if (ctx != AugStore) {
5035 if (!compiler_slice(c, s, ctx))
5036 return 0;
5037 }
5038 break;
5039 case ExtSlice_kind:
5040 kindname = "extended slice";
5041 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005042 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 for (i = 0; i < n; i++) {
5044 slice_ty sub = (slice_ty)asdl_seq_GET(
5045 s->v.ExtSlice.dims, i);
5046 if (!compiler_visit_nested_slice(c, sub, ctx))
5047 return 0;
5048 }
5049 ADDOP_I(c, BUILD_TUPLE, n);
5050 }
5051 break;
5052 default:
5053 PyErr_Format(PyExc_SystemError,
5054 "invalid subscript kind %d", s->kind);
5055 return 0;
5056 }
5057 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005058}
5059
Thomas Wouters89f507f2006-12-13 04:49:30 +00005060/* End of the compiler section, beginning of the assembler section */
5061
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005062/* do depth-first search of basic block graph, starting with block.
5063 post records the block indices in post-order.
5064
5065 XXX must handle implicit jumps from one block to next
5066*/
5067
Thomas Wouters89f507f2006-12-13 04:49:30 +00005068struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 PyObject *a_bytecode; /* string containing bytecode */
5070 int a_offset; /* offset into bytecode */
5071 int a_nblocks; /* number of reachable blocks */
5072 basicblock **a_postorder; /* list of blocks in dfs postorder */
5073 PyObject *a_lnotab; /* string containing lnotab */
5074 int a_lnotab_off; /* offset into lnotab */
5075 int a_lineno; /* last lineno of emitted instruction */
5076 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005077};
5078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005079static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005080dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005081{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005082 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005083
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005084 /* Get rid of recursion for normal control flow.
5085 Since the number of blocks is limited, unused space in a_postorder
5086 (from a_nblocks to end) can be used as a stack for still not ordered
5087 blocks. */
5088 for (j = end; b && !b->b_seen; b = b->b_next) {
5089 b->b_seen = 1;
5090 assert(a->a_nblocks < j);
5091 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005093 while (j < end) {
5094 b = a->a_postorder[j++];
5095 for (i = 0; i < b->b_iused; i++) {
5096 struct instr *instr = &b->b_instr[i];
5097 if (instr->i_jrel || instr->i_jabs)
5098 dfs(c, instr->i_target, a, j);
5099 }
5100 assert(a->a_nblocks < j);
5101 a->a_postorder[a->a_nblocks++] = b;
5102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005103}
5104
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005105Py_LOCAL_INLINE(void)
5106stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005108 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005109 if (b->b_startdepth < depth) {
5110 assert(b->b_startdepth < 0);
5111 b->b_startdepth = depth;
5112 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005113 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005114}
5115
5116/* Find the flow path that needs the largest stack. We assume that
5117 * cycles in the flow graph have no net effect on the stack depth.
5118 */
5119static int
5120stackdepth(struct compiler *c)
5121{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005122 basicblock *b, *entryblock = NULL;
5123 basicblock **stack, **sp;
5124 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 b->b_startdepth = INT_MIN;
5127 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005128 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 }
5130 if (!entryblock)
5131 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005132 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5133 if (!stack) {
5134 PyErr_NoMemory();
5135 return -1;
5136 }
5137
5138 sp = stack;
5139 stackdepth_push(&sp, entryblock, 0);
5140 while (sp != stack) {
5141 b = *--sp;
5142 int depth = b->b_startdepth;
5143 assert(depth >= 0);
5144 basicblock *next = b->b_next;
5145 for (int i = 0; i < b->b_iused; i++) {
5146 struct instr *instr = &b->b_instr[i];
5147 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5148 if (effect == PY_INVALID_STACK_EFFECT) {
5149 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5150 Py_FatalError("PyCompile_OpcodeStackEffect()");
5151 }
5152 int new_depth = depth + effect;
5153 if (new_depth > maxdepth) {
5154 maxdepth = new_depth;
5155 }
5156 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5157 if (instr->i_jrel || instr->i_jabs) {
5158 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5159 assert(effect != PY_INVALID_STACK_EFFECT);
5160 int target_depth = depth + effect;
5161 if (target_depth > maxdepth) {
5162 maxdepth = target_depth;
5163 }
5164 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005165 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005166 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005167 assert(instr->i_target->b_startdepth >= target_depth);
5168 depth = new_depth;
5169 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005170 }
5171 stackdepth_push(&sp, instr->i_target, target_depth);
5172 }
5173 depth = new_depth;
5174 if (instr->i_opcode == JUMP_ABSOLUTE ||
5175 instr->i_opcode == JUMP_FORWARD ||
5176 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005177 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005178 {
5179 /* remaining code is dead */
5180 next = NULL;
5181 break;
5182 }
5183 }
5184 if (next != NULL) {
5185 stackdepth_push(&sp, next, depth);
5186 }
5187 }
5188 PyObject_Free(stack);
5189 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005190}
5191
5192static int
5193assemble_init(struct assembler *a, int nblocks, int firstlineno)
5194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 memset(a, 0, sizeof(struct assembler));
5196 a->a_lineno = firstlineno;
5197 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5198 if (!a->a_bytecode)
5199 return 0;
5200 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5201 if (!a->a_lnotab)
5202 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005203 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PyErr_NoMemory();
5205 return 0;
5206 }
5207 a->a_postorder = (basicblock **)PyObject_Malloc(
5208 sizeof(basicblock *) * nblocks);
5209 if (!a->a_postorder) {
5210 PyErr_NoMemory();
5211 return 0;
5212 }
5213 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005214}
5215
5216static void
5217assemble_free(struct assembler *a)
5218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 Py_XDECREF(a->a_bytecode);
5220 Py_XDECREF(a->a_lnotab);
5221 if (a->a_postorder)
5222 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005223}
5224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005225static int
5226blocksize(basicblock *b)
5227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 int i;
5229 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005232 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005234}
5235
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005236/* Appends a pair to the end of the line number table, a_lnotab, representing
5237 the instruction's bytecode offset and line number. See
5238 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005239
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005240static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005241assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005244 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005246
Serhiy Storchakaab874002016-09-11 13:48:15 +03005247 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 if(d_bytecode == 0 && d_lineno == 0)
5253 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (d_bytecode > 255) {
5256 int j, nbytes, ncodes = d_bytecode / 255;
5257 nbytes = a->a_lnotab_off + 2 * ncodes;
5258 len = PyBytes_GET_SIZE(a->a_lnotab);
5259 if (nbytes >= len) {
5260 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5261 len = nbytes;
5262 else if (len <= INT_MAX / 2)
5263 len *= 2;
5264 else {
5265 PyErr_NoMemory();
5266 return 0;
5267 }
5268 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5269 return 0;
5270 }
5271 lnotab = (unsigned char *)
5272 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5273 for (j = 0; j < ncodes; j++) {
5274 *lnotab++ = 255;
5275 *lnotab++ = 0;
5276 }
5277 d_bytecode -= ncodes * 255;
5278 a->a_lnotab_off += ncodes * 2;
5279 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005280 assert(0 <= d_bytecode && d_bytecode <= 255);
5281
5282 if (d_lineno < -128 || 127 < d_lineno) {
5283 int j, nbytes, ncodes, k;
5284 if (d_lineno < 0) {
5285 k = -128;
5286 /* use division on positive numbers */
5287 ncodes = (-d_lineno) / 128;
5288 }
5289 else {
5290 k = 127;
5291 ncodes = d_lineno / 127;
5292 }
5293 d_lineno -= ncodes * k;
5294 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 nbytes = a->a_lnotab_off + 2 * ncodes;
5296 len = PyBytes_GET_SIZE(a->a_lnotab);
5297 if (nbytes >= len) {
5298 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5299 len = nbytes;
5300 else if (len <= INT_MAX / 2)
5301 len *= 2;
5302 else {
5303 PyErr_NoMemory();
5304 return 0;
5305 }
5306 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5307 return 0;
5308 }
5309 lnotab = (unsigned char *)
5310 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5311 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005312 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 d_bytecode = 0;
5314 for (j = 1; j < ncodes; j++) {
5315 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005316 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 a->a_lnotab_off += ncodes * 2;
5319 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005320 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 len = PyBytes_GET_SIZE(a->a_lnotab);
5323 if (a->a_lnotab_off + 2 >= len) {
5324 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5325 return 0;
5326 }
5327 lnotab = (unsigned char *)
5328 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 a->a_lnotab_off += 2;
5331 if (d_bytecode) {
5332 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005333 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 }
5335 else { /* First line of a block; def stmt, etc. */
5336 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005337 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 }
5339 a->a_lineno = i->i_lineno;
5340 a->a_lineno_off = a->a_offset;
5341 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005342}
5343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005344/* assemble_emit()
5345 Extend the bytecode with a new instruction.
5346 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005347*/
5348
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005349static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005351{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005352 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005354 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005355
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005356 arg = i->i_oparg;
5357 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 if (i->i_lineno && !assemble_lnotab(a, i))
5359 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005360 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 if (len > PY_SSIZE_T_MAX / 2)
5362 return 0;
5363 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5364 return 0;
5365 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005366 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005368 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005370}
5371
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005372static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005376 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 /* Compute the size of each block and fixup jump args.
5380 Replace block pointer with position in bytecode. */
5381 do {
5382 totsize = 0;
5383 for (i = a->a_nblocks - 1; i >= 0; i--) {
5384 b = a->a_postorder[i];
5385 bsize = blocksize(b);
5386 b->b_offset = totsize;
5387 totsize += bsize;
5388 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005389 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5391 bsize = b->b_offset;
5392 for (i = 0; i < b->b_iused; i++) {
5393 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005394 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 /* Relative jumps are computed relative to
5396 the instruction pointer after fetching
5397 the jump instruction.
5398 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005399 bsize += isize;
5400 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005402 if (instr->i_jrel) {
5403 instr->i_oparg -= bsize;
5404 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005405 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005406 if (instrsize(instr->i_oparg) != isize) {
5407 extended_arg_recompile = 1;
5408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 }
5411 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 /* XXX: This is an awful hack that could hurt performance, but
5414 on the bright side it should work until we come up
5415 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 The issue is that in the first loop blocksize() is called
5418 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005419 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 So we loop until we stop seeing new EXTENDED_ARGs.
5423 The only EXTENDED_ARGs that could be popping up are
5424 ones in jump instructions. So this should converge
5425 fairly quickly.
5426 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005427 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005428}
5429
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005430static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005431dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005434 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 tuple = PyTuple_New(size);
5437 if (tuple == NULL)
5438 return NULL;
5439 while (PyDict_Next(dict, &pos, &k, &v)) {
5440 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005441 Py_INCREF(k);
5442 assert((i - offset) < size);
5443 assert((i - offset) >= 0);
5444 PyTuple_SET_ITEM(tuple, i - offset, k);
5445 }
5446 return tuple;
5447}
5448
5449static PyObject *
5450consts_dict_keys_inorder(PyObject *dict)
5451{
5452 PyObject *consts, *k, *v;
5453 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5454
5455 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5456 if (consts == NULL)
5457 return NULL;
5458 while (PyDict_Next(dict, &pos, &k, &v)) {
5459 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005460 /* The keys of the dictionary can be tuples wrapping a contant.
5461 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5462 * the object we want is always second. */
5463 if (PyTuple_CheckExact(k)) {
5464 k = PyTuple_GET_ITEM(k, 1);
5465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005467 assert(i < size);
5468 assert(i >= 0);
5469 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005471 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005472}
5473
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005474static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005478 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005480 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 if (ste->ste_nested)
5482 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005483 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005485 if (!ste->ste_generator && ste->ste_coroutine)
5486 flags |= CO_COROUTINE;
5487 if (ste->ste_generator && ste->ste_coroutine)
5488 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 if (ste->ste_varargs)
5490 flags |= CO_VARARGS;
5491 if (ste->ste_varkeywords)
5492 flags |= CO_VARKEYWORDS;
5493 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 /* (Only) inherit compilerflags in PyCF_MASK */
5496 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005499}
5500
INADA Naokic2e16072018-11-26 21:23:22 +09005501// Merge *tuple* with constant cache.
5502// Unlike merge_consts_recursive(), this function doesn't work recursively.
5503static int
5504merge_const_tuple(struct compiler *c, PyObject **tuple)
5505{
5506 assert(PyTuple_CheckExact(*tuple));
5507
5508 PyObject *key = _PyCode_ConstantKey(*tuple);
5509 if (key == NULL) {
5510 return 0;
5511 }
5512
5513 // t is borrowed reference
5514 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5515 Py_DECREF(key);
5516 if (t == NULL) {
5517 return 0;
5518 }
5519 if (t == key) { // tuple is new constant.
5520 return 1;
5521 }
5522
5523 PyObject *u = PyTuple_GET_ITEM(t, 1);
5524 Py_INCREF(u);
5525 Py_DECREF(*tuple);
5526 *tuple = u;
5527 return 1;
5528}
5529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005530static PyCodeObject *
5531makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 PyObject *tmp;
5534 PyCodeObject *co = NULL;
5535 PyObject *consts = NULL;
5536 PyObject *names = NULL;
5537 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 PyObject *name = NULL;
5539 PyObject *freevars = NULL;
5540 PyObject *cellvars = NULL;
5541 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005542 Py_ssize_t nlocals;
5543 int nlocals_int;
5544 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005545 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005546
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005547 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 names = dict_keys_inorder(c->u->u_names, 0);
5549 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5550 if (!consts || !names || !varnames)
5551 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5554 if (!cellvars)
5555 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005556 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005557 if (!freevars)
5558 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005559
INADA Naokic2e16072018-11-26 21:23:22 +09005560 if (!merge_const_tuple(c, &names) ||
5561 !merge_const_tuple(c, &varnames) ||
5562 !merge_const_tuple(c, &cellvars) ||
5563 !merge_const_tuple(c, &freevars))
5564 {
5565 goto error;
5566 }
5567
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005568 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005569 assert(nlocals < INT_MAX);
5570 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 flags = compute_code_flags(c);
5573 if (flags < 0)
5574 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5577 if (!bytecode)
5578 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5581 if (!tmp)
5582 goto error;
5583 Py_DECREF(consts);
5584 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005585 if (!merge_const_tuple(c, &consts)) {
5586 goto error;
5587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588
Victor Stinnerf8e32212013-11-19 23:56:34 +01005589 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5590 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005591 maxdepth = stackdepth(c);
5592 if (maxdepth < 0) {
5593 goto error;
5594 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005595 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005596 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 bytecode, consts, names, varnames,
5598 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005599 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 c->u->u_firstlineno,
5601 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005602 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 Py_XDECREF(consts);
5604 Py_XDECREF(names);
5605 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 Py_XDECREF(name);
5607 Py_XDECREF(freevars);
5608 Py_XDECREF(cellvars);
5609 Py_XDECREF(bytecode);
5610 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005611}
5612
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005613
5614/* For debugging purposes only */
5615#if 0
5616static void
5617dump_instr(const struct instr *i)
5618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 const char *jrel = i->i_jrel ? "jrel " : "";
5620 const char *jabs = i->i_jabs ? "jabs " : "";
5621 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005624 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5628 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005629}
5630
5631static void
5632dump_basicblock(const basicblock *b)
5633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 const char *seen = b->b_seen ? "seen " : "";
5635 const char *b_return = b->b_return ? "return " : "";
5636 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5637 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5638 if (b->b_instr) {
5639 int i;
5640 for (i = 0; i < b->b_iused; i++) {
5641 fprintf(stderr, " [%02d] ", i);
5642 dump_instr(b->b_instr + i);
5643 }
5644 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005645}
5646#endif
5647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005648static PyCodeObject *
5649assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 basicblock *b, *entryblock;
5652 struct assembler a;
5653 int i, j, nblocks;
5654 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 /* Make sure every block that falls off the end returns None.
5657 XXX NEXT_BLOCK() isn't quite right, because if the last
5658 block ends with a jump or return b_next shouldn't set.
5659 */
5660 if (!c->u->u_curblock->b_return) {
5661 NEXT_BLOCK(c);
5662 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005663 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 ADDOP(c, RETURN_VALUE);
5665 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 nblocks = 0;
5668 entryblock = NULL;
5669 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5670 nblocks++;
5671 entryblock = b;
5672 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 /* Set firstlineno if it wasn't explicitly set. */
5675 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005676 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5678 else
5679 c->u->u_firstlineno = 1;
5680 }
5681 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5682 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005683 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 /* Can't modify the bytecode after computing jump offsets. */
5686 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 /* Emit code in reverse postorder from dfs. */
5689 for (i = a.a_nblocks - 1; i >= 0; i--) {
5690 b = a.a_postorder[i];
5691 for (j = 0; j < b->b_iused; j++)
5692 if (!assemble_emit(&a, &b->b_instr[j]))
5693 goto error;
5694 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5697 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005698 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005702 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 assemble_free(&a);
5704 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005705}
Georg Brandl8334fd92010-12-04 10:26:46 +00005706
5707#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005708PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005709PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5710 PyArena *arena)
5711{
5712 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5713}