blob: f56c015fb96a3941de87bd3e07bf0c3f8e50ceff [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"
Victor Stinnerc96be812019-05-14 17:34:56 +020027#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200200static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500202static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400203static int compiler_async_with(struct compiler *, stmt_ty, int);
204static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100205static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400207 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500208static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400209static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000210
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700211static int compiler_sync_comprehension_generator(
212 struct compiler *c,
213 asdl_seq *generators, int gen_index,
214 expr_ty elt, expr_ty val, int type);
215
216static int compiler_async_comprehension_generator(
217 struct compiler *c,
218 asdl_seq *generators, int gen_index,
219 expr_ty elt, expr_ty val, int type);
220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000222static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400224#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 /* Name mangling: __private becomes _classname__private.
230 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200231 PyObject *result;
232 size_t nlen, plen, ipriv;
233 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 PyUnicode_READ_CHAR(ident, 0) != '_' ||
236 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident;
239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200240 nlen = PyUnicode_GET_LENGTH(ident);
241 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 The only time a name with a dot can occur is when
245 we are compiling an import statement that has a
246 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 TODO(jhylton): Decide whether we want to support
249 mangling of the module name, e.g. __M.X.
250 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200251 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
252 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
253 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_INCREF(ident);
255 return ident; /* Don't mangle __whatever__ */
256 }
257 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258 ipriv = 0;
259 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
260 ipriv++;
261 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 Py_INCREF(ident);
263 return ident; /* Don't mangle if class is just underscores */
264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Antoine Pitrou55bff892013-04-06 21:21:04 +0200267 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
268 PyErr_SetString(PyExc_OverflowError,
269 "private identifier too large to be mangled");
270 return NULL;
271 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
274 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
275 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
276
277 result = PyUnicode_New(1 + nlen + plen, maxchar);
278 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
281 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200282 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
283 Py_DECREF(result);
284 return NULL;
285 }
286 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
287 Py_DECREF(result);
288 return NULL;
289 }
Victor Stinner8f825062012-04-27 13:55:39 +0200290 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000292}
293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294static int
295compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000298
INADA Naokic2e16072018-11-26 21:23:22 +0900299 c->c_const_cache = PyDict_New();
300 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900302 }
303
304 c->c_stack = PyList_New(0);
305 if (!c->c_stack) {
306 Py_CLEAR(c->c_const_cache);
307 return 0;
308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311}
312
313PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200314PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
315 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 struct compiler c;
318 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200319 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200321 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!__doc__) {
324 __doc__ = PyUnicode_InternFromString("__doc__");
325 if (!__doc__)
326 return NULL;
327 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000328 if (!__annotations__) {
329 __annotations__ = PyUnicode_InternFromString("__annotations__");
330 if (!__annotations__)
331 return NULL;
332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (!compiler_init(&c))
334 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200335 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 c.c_filename = filename;
337 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (c.c_future == NULL)
340 goto finally;
341 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 flags = &local_flags;
343 }
344 merged = c.c_future->ff_features | flags->cf_flags;
345 c.c_future->ff_features = merged;
346 flags->cf_flags = merged;
347 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200348 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100350 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200352 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900353 goto finally;
354 }
355
Victor Stinner14e461d2013-08-26 22:28:21 +0200356 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (c.c_st == NULL) {
358 if (!PyErr_Occurred())
359 PyErr_SetString(PyExc_SystemError, "no symtable");
360 goto finally;
361 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364
Thomas Wouters1175c432006-02-27 22:49:54 +0000365 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 compiler_free(&c);
367 assert(co || PyErr_Occurred());
368 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369}
370
371PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200372PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
373 int optimize, PyArena *arena)
374{
375 PyObject *filename;
376 PyCodeObject *co;
377 filename = PyUnicode_DecodeFSDefault(filename_str);
378 if (filename == NULL)
379 return NULL;
380 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
381 Py_DECREF(filename);
382 return co;
383
384}
385
386PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387PyNode_Compile(struct _node *n, const char *filename)
388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyCodeObject *co = NULL;
390 mod_ty mod;
391 PyArena *arena = PyArena_New();
392 if (!arena)
393 return NULL;
394 mod = PyAST_FromNode(n, NULL, filename, arena);
395 if (mod)
396 co = PyAST_Compile(mod, filename, NULL, arena);
397 PyArena_Free(arena);
398 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000399}
400
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (c->c_st)
405 PySymtable_Free(c->c_st);
406 if (c->c_future)
407 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200408 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900409 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000411}
412
Guido van Rossum79f25d91997-04-29 20:08:16 +0000413static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 Py_ssize_t i, n;
417 PyObject *v, *k;
418 PyObject *dict = PyDict_New();
419 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 n = PyList_Size(list);
422 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100423 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (!v) {
425 Py_DECREF(dict);
426 return NULL;
427 }
428 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300429 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 Py_DECREF(v);
431 Py_DECREF(dict);
432 return NULL;
433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 Py_DECREF(v);
435 }
436 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437}
438
439/* Return new dict containing names from src that match scope(s).
440
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000441src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443values are integers, starting at offset and increasing by one for
444each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445*/
446
447static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100448dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700450 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500452 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 assert(offset >= 0);
455 if (dest == NULL)
456 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000457
Meador Inge2ca63152012-07-18 14:20:11 -0500458 /* Sort the keys so that we have a deterministic order on the indexes
459 saved in the returned dictionary. These indexes are used as indexes
460 into the free and cell var storage. Therefore if they aren't
461 deterministic, then the generated bytecode is not deterministic.
462 */
463 sorted_keys = PyDict_Keys(src);
464 if (sorted_keys == NULL)
465 return NULL;
466 if (PyList_Sort(sorted_keys) != 0) {
467 Py_DECREF(sorted_keys);
468 return NULL;
469 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500470 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500471
472 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* XXX this should probably be a macro in symtable.h */
474 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500475 k = PyList_GET_ITEM(sorted_keys, key_i);
476 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 assert(PyLong_Check(v));
478 vi = PyLong_AS_LONG(v);
479 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300482 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500484 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 Py_DECREF(dest);
486 return NULL;
487 }
488 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300489 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500490 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_DECREF(item);
492 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return NULL;
494 }
495 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
497 }
Meador Inge2ca63152012-07-18 14:20:11 -0500498 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000500}
501
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502static void
503compiler_unit_check(struct compiler_unit *u)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 basicblock *block;
506 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700507 assert((uintptr_t)block != 0xcbcbcbcbU);
508 assert((uintptr_t)block != 0xfbfbfbfbU);
509 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (block->b_instr != NULL) {
511 assert(block->b_ialloc > 0);
512 assert(block->b_iused > 0);
513 assert(block->b_ialloc >= block->b_iused);
514 }
515 else {
516 assert (block->b_iused == 0);
517 assert (block->b_ialloc == 0);
518 }
519 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520}
521
522static void
523compiler_unit_free(struct compiler_unit *u)
524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 compiler_unit_check(u);
528 b = u->u_blocks;
529 while (b != NULL) {
530 if (b->b_instr)
531 PyObject_Free((void *)b->b_instr);
532 next = b->b_list;
533 PyObject_Free((void *)b);
534 b = next;
535 }
536 Py_CLEAR(u->u_ste);
537 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400538 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 Py_CLEAR(u->u_consts);
540 Py_CLEAR(u->u_names);
541 Py_CLEAR(u->u_varnames);
542 Py_CLEAR(u->u_freevars);
543 Py_CLEAR(u->u_cellvars);
544 Py_CLEAR(u->u_private);
545 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
548static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100549compiler_enter_scope(struct compiler *c, identifier name,
550 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100553 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
556 struct compiler_unit));
557 if (!u) {
558 PyErr_NoMemory();
559 return 0;
560 }
561 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100562 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100564 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 u->u_kwonlyargcount = 0;
566 u->u_ste = PySymtable_Lookup(c->c_st, key);
567 if (!u->u_ste) {
568 compiler_unit_free(u);
569 return 0;
570 }
571 Py_INCREF(name);
572 u->u_name = name;
573 u->u_varnames = list2dict(u->u_ste->ste_varnames);
574 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
575 if (!u->u_varnames || !u->u_cellvars) {
576 compiler_unit_free(u);
577 return 0;
578 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000580 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300582 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 int res;
584 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200585 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500586 name = _PyUnicode_FromId(&PyId___class__);
587 if (!name) {
588 compiler_unit_free(u);
589 return 0;
590 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300591 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500592 if (res < 0) {
593 compiler_unit_free(u);
594 return 0;
595 }
596 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200599 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!u->u_freevars) {
601 compiler_unit_free(u);
602 return 0;
603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_blocks = NULL;
606 u->u_nfblocks = 0;
607 u->u_firstlineno = lineno;
608 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000609 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_lineno_set = 0;
611 u->u_consts = PyDict_New();
612 if (!u->u_consts) {
613 compiler_unit_free(u);
614 return 0;
615 }
616 u->u_names = PyDict_New();
617 if (!u->u_names) {
618 compiler_unit_free(u);
619 return 0;
620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 /* Push the old compiler_unit on the stack. */
625 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400626 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
628 Py_XDECREF(capsule);
629 compiler_unit_free(u);
630 return 0;
631 }
632 Py_DECREF(capsule);
633 u->u_private = c->u->u_private;
634 Py_XINCREF(u->u_private);
635 }
636 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100639
640 block = compiler_new_block(c);
641 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100643 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400645 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
646 if (!compiler_set_qualname(c))
647 return 0;
648 }
649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000651}
652
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000653static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654compiler_exit_scope(struct compiler *c)
655{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100656 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 c->c_nestlevel--;
660 compiler_unit_free(c->u);
661 /* Restore c->u to the parent unit. */
662 n = PyList_GET_SIZE(c->c_stack) - 1;
663 if (n >= 0) {
664 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400665 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 assert(c->u);
667 /* we are deleting from a list so this really shouldn't fail */
668 if (PySequence_DelItem(c->c_stack, n) < 0)
669 Py_FatalError("compiler_exit_scope()");
670 compiler_unit_check(c->u);
671 }
672 else
673 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675}
676
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677static int
678compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 _Py_static_string(dot_locals, ".<locals>");
682 Py_ssize_t stack_size;
683 struct compiler_unit *u = c->u;
684 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100685
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100687 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400688 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 if (stack_size > 1) {
690 int scope, force_global = 0;
691 struct compiler_unit *parent;
692 PyObject *mangled, *capsule;
693
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400694 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400695 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 assert(parent);
697
Yury Selivanov75445082015-05-11 22:57:16 -0400698 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
699 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
700 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400701 assert(u->u_name);
702 mangled = _Py_Mangle(parent->u_private, u->u_name);
703 if (!mangled)
704 return 0;
705 scope = PyST_GetScope(parent->u_ste, mangled);
706 Py_DECREF(mangled);
707 assert(scope != GLOBAL_IMPLICIT);
708 if (scope == GLOBAL_EXPLICIT)
709 force_global = 1;
710 }
711
712 if (!force_global) {
713 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400714 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
716 dot_locals_str = _PyUnicode_FromId(&dot_locals);
717 if (dot_locals_str == NULL)
718 return 0;
719 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
720 if (base == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(parent->u_qualname);
725 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400726 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100727 }
728 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400729
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400730 if (base != NULL) {
731 dot_str = _PyUnicode_FromId(&dot);
732 if (dot_str == NULL) {
733 Py_DECREF(base);
734 return 0;
735 }
736 name = PyUnicode_Concat(base, dot_str);
737 Py_DECREF(base);
738 if (name == NULL)
739 return 0;
740 PyUnicode_Append(&name, u->u_name);
741 if (name == NULL)
742 return 0;
743 }
744 else {
745 Py_INCREF(u->u_name);
746 name = u->u_name;
747 }
748 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100749
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400750 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100751}
752
Eric V. Smith235a6f02015-09-19 14:51:32 -0400753
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754/* Allocate a new block and return a pointer to it.
755 Returns NULL on error.
756*/
757
758static basicblock *
759compiler_new_block(struct compiler *c)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 basicblock *b;
762 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 u = c->u;
765 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
766 if (b == NULL) {
767 PyErr_NoMemory();
768 return NULL;
769 }
770 memset((void *)b, 0, sizeof(basicblock));
771 /* Extend the singly linked list of blocks with new block. */
772 b->b_list = u->u_blocks;
773 u->u_blocks = b;
774 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778compiler_next_block(struct compiler *c)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 basicblock *block = compiler_new_block(c);
781 if (block == NULL)
782 return NULL;
783 c->u->u_curblock->b_next = block;
784 c->u->u_curblock = block;
785 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786}
787
788static basicblock *
789compiler_use_next_block(struct compiler *c, basicblock *block)
790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 assert(block != NULL);
792 c->u->u_curblock->b_next = block;
793 c->u->u_curblock = block;
794 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795}
796
797/* Returns the offset of the next instruction in the current block's
798 b_instr array. Resizes the b_instr as necessary.
799 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000801
802static int
803compiler_next_instr(struct compiler *c, basicblock *b)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 assert(b != NULL);
806 if (b->b_instr == NULL) {
807 b->b_instr = (struct instr *)PyObject_Malloc(
808 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
809 if (b->b_instr == NULL) {
810 PyErr_NoMemory();
811 return -1;
812 }
813 b->b_ialloc = DEFAULT_BLOCK_SIZE;
814 memset((char *)b->b_instr, 0,
815 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
816 }
817 else if (b->b_iused == b->b_ialloc) {
818 struct instr *tmp;
819 size_t oldsize, newsize;
820 oldsize = b->b_ialloc * sizeof(struct instr);
821 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000822
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700823 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PyErr_NoMemory();
825 return -1;
826 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (newsize == 0) {
829 PyErr_NoMemory();
830 return -1;
831 }
832 b->b_ialloc <<= 1;
833 tmp = (struct instr *)PyObject_Realloc(
834 (void *)b->b_instr, newsize);
835 if (tmp == NULL) {
836 PyErr_NoMemory();
837 return -1;
838 }
839 b->b_instr = tmp;
840 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
841 }
842 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843}
844
Christian Heimes2202f872008-02-06 14:31:34 +0000845/* Set the i_lineno member of the instruction at offset off if the
846 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847 already been set. If it has been set, the call has no effect.
848
Christian Heimes2202f872008-02-06 14:31:34 +0000849 The line number is reset in the following cases:
850 - when entering a new scope
851 - on each statement
852 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200853 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000854 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000857static void
858compiler_set_lineno(struct compiler *c, int off)
859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 basicblock *b;
861 if (c->u->u_lineno_set)
862 return;
863 c->u->u_lineno_set = 1;
864 b = c->u->u_curblock;
865 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866}
867
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200868/* Return the stack effect of opcode with argument oparg.
869
870 Some opcodes have different stack effect when jump to the target and
871 when not jump. The 'jump' parameter specifies the case:
872
873 * 0 -- when not jump
874 * 1 -- when jump
875 * -1 -- maximal
876 */
877/* XXX Make the stack effect of WITH_CLEANUP_START and
878 WITH_CLEANUP_FINISH deterministic. */
879static int
880stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300883 case NOP:
884 case EXTENDED_ARG:
885 return 0;
886
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200887 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case POP_TOP:
889 return -1;
890 case ROT_TWO:
891 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200892 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 return 0;
894 case DUP_TOP:
895 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000896 case DUP_TOP_TWO:
897 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000898
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200899 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case UNARY_POSITIVE:
901 case UNARY_NEGATIVE:
902 case UNARY_NOT:
903 case UNARY_INVERT:
904 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case SET_ADD:
907 case LIST_APPEND:
908 return -1;
909 case MAP_ADD:
910 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000911
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200912 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case BINARY_POWER:
914 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400915 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case BINARY_MODULO:
917 case BINARY_ADD:
918 case BINARY_SUBTRACT:
919 case BINARY_SUBSCR:
920 case BINARY_FLOOR_DIVIDE:
921 case BINARY_TRUE_DIVIDE:
922 return -1;
923 case INPLACE_FLOOR_DIVIDE:
924 case INPLACE_TRUE_DIVIDE:
925 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case INPLACE_ADD:
928 case INPLACE_SUBTRACT:
929 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400930 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 case INPLACE_MODULO:
932 return -1;
933 case STORE_SUBSCR:
934 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case DELETE_SUBSCR:
936 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case BINARY_LSHIFT:
939 case BINARY_RSHIFT:
940 case BINARY_AND:
941 case BINARY_XOR:
942 case BINARY_OR:
943 return -1;
944 case INPLACE_POWER:
945 return -1;
946 case GET_ITER:
947 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case PRINT_EXPR:
950 return -1;
951 case LOAD_BUILD_CLASS:
952 return 1;
953 case INPLACE_LSHIFT:
954 case INPLACE_RSHIFT:
955 case INPLACE_AND:
956 case INPLACE_XOR:
957 case INPLACE_OR:
958 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200961 /* 1 in the normal flow.
962 * Restore the stack position and push 6 values before jumping to
963 * the handler if an exception be raised. */
964 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case RETURN_VALUE:
966 return -1;
967 case IMPORT_STAR:
968 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700969 case SETUP_ANNOTATIONS:
970 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case YIELD_VALUE:
972 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500973 case YIELD_FROM:
974 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case POP_BLOCK:
976 return 0;
977 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200978 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 case STORE_NAME:
981 return -1;
982 case DELETE_NAME:
983 return 0;
984 case UNPACK_SEQUENCE:
985 return oparg-1;
986 case UNPACK_EX:
987 return (oparg&0xFF) + (oparg>>8);
988 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* -1 at end of iterator, 1 if continue iterating. */
990 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case STORE_ATTR:
993 return -2;
994 case DELETE_ATTR:
995 return -1;
996 case STORE_GLOBAL:
997 return -1;
998 case DELETE_GLOBAL:
999 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case LOAD_CONST:
1001 return 1;
1002 case LOAD_NAME:
1003 return 1;
1004 case BUILD_TUPLE:
1005 case BUILD_LIST:
1006 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001007 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001009 case BUILD_LIST_UNPACK:
1010 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001011 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001012 case BUILD_SET_UNPACK:
1013 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001014 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001015 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001017 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001018 case BUILD_CONST_KEY_MAP:
1019 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_ATTR:
1021 return 0;
1022 case COMPARE_OP:
1023 return -1;
1024 case IMPORT_NAME:
1025 return -1;
1026 case IMPORT_FROM:
1027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001029 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_ABSOLUTE:
1032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001034 case JUMP_IF_TRUE_OR_POP:
1035 case JUMP_IF_FALSE_OR_POP:
1036 return jump ? 0 : -1;
1037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case POP_JUMP_IF_FALSE:
1039 case POP_JUMP_IF_TRUE:
1040 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_GLOBAL:
1043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001045 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001047 /* 0 in the normal flow.
1048 * Restore the stack position and push 6 values before jumping to
1049 * the handler if an exception be raised. */
1050 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001051 case RERAISE:
1052 return -3;
1053
1054 case WITH_EXCEPT_START:
1055 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case LOAD_FAST:
1058 return 1;
1059 case STORE_FAST:
1060 return -1;
1061 case DELETE_FAST:
1062 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case RAISE_VARARGS:
1065 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066
1067 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001069 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001070 case CALL_METHOD:
1071 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001073 return -oparg-1;
1074 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001075 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001076 case MAKE_FUNCTION:
1077 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1078 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case BUILD_SLICE:
1080 if (oparg == 3)
1081 return -2;
1082 else
1083 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001084
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 case LOAD_CLOSURE:
1087 return 1;
1088 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001089 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return 1;
1091 case STORE_DEREF:
1092 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001093 case DELETE_DEREF:
1094 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001095
1096 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001097 case GET_AWAITABLE:
1098 return 0;
1099 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100 /* 0 in the normal flow.
1101 * Restore the stack position to the position before the result
1102 * of __aenter__ and push 6 values before jumping to the handler
1103 * if an exception be raised. */
1104 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001105 case BEFORE_ASYNC_WITH:
1106 return 1;
1107 case GET_AITER:
1108 return 0;
1109 case GET_ANEXT:
1110 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001111 case GET_YIELD_FROM_ITER:
1112 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001113 case END_ASYNC_FOR:
1114 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001115 case FORMAT_VALUE:
1116 /* If there's a fmt_spec on the stack, we go from 2->1,
1117 else 1->1. */
1118 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001119 case LOAD_METHOD:
1120 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001121 case LOAD_ASSERTION_ERROR:
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));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001152 if (c->c_do_not_emit_bytecode) {
1153 return 1;
1154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 off = compiler_next_instr(c, c->u->u_curblock);
1156 if (off < 0)
1157 return 0;
1158 b = c->u->u_curblock;
1159 i = &b->b_instr[off];
1160 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001161 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (opcode == RETURN_VALUE)
1163 b->b_return = 1;
1164 compiler_set_lineno(c, off);
1165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
Victor Stinnerf8e32212013-11-19 23:56:34 +01001168static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1170{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001174 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001176 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001178 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001179 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001180 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return -1;
1183 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001184 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 Py_DECREF(v);
1186 return -1;
1187 }
1188 Py_DECREF(v);
1189 }
1190 else
1191 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001192 return arg;
1193}
1194
INADA Naokic2e16072018-11-26 21:23:22 +09001195// Merge const *o* recursively and return constant key object.
1196static PyObject*
1197merge_consts_recursive(struct compiler *c, PyObject *o)
1198{
1199 // None and Ellipsis are singleton, and key is the singleton.
1200 // No need to merge object and key.
1201 if (o == Py_None || o == Py_Ellipsis) {
1202 Py_INCREF(o);
1203 return o;
1204 }
1205
1206 PyObject *key = _PyCode_ConstantKey(o);
1207 if (key == NULL) {
1208 return NULL;
1209 }
1210
1211 // t is borrowed reference
1212 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1213 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001214 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001215 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001216 Py_DECREF(key);
1217 return t;
1218 }
1219
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001221 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001223 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 Py_ssize_t len = PyTuple_GET_SIZE(o);
1225 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001226 PyObject *item = PyTuple_GET_ITEM(o, i);
1227 PyObject *u = merge_consts_recursive(c, item);
1228 if (u == NULL) {
1229 Py_DECREF(key);
1230 return NULL;
1231 }
1232
1233 // See _PyCode_ConstantKey()
1234 PyObject *v; // borrowed
1235 if (PyTuple_CheckExact(u)) {
1236 v = PyTuple_GET_ITEM(u, 1);
1237 }
1238 else {
1239 v = u;
1240 }
1241 if (v != item) {
1242 Py_INCREF(v);
1243 PyTuple_SET_ITEM(o, i, v);
1244 Py_DECREF(item);
1245 }
1246
1247 Py_DECREF(u);
1248 }
1249 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001250 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001251 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 // constant keys.
1253 // See _PyCode_ConstantKey() for detail.
1254 assert(PyTuple_CheckExact(key));
1255 assert(PyTuple_GET_SIZE(key) == 2);
1256
1257 Py_ssize_t len = PySet_GET_SIZE(o);
1258 if (len == 0) { // empty frozenset should not be re-created.
1259 return key;
1260 }
1261 PyObject *tuple = PyTuple_New(len);
1262 if (tuple == NULL) {
1263 Py_DECREF(key);
1264 return NULL;
1265 }
1266 Py_ssize_t i = 0, pos = 0;
1267 PyObject *item;
1268 Py_hash_t hash;
1269 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1270 PyObject *k = merge_consts_recursive(c, item);
1271 if (k == NULL) {
1272 Py_DECREF(tuple);
1273 Py_DECREF(key);
1274 return NULL;
1275 }
1276 PyObject *u;
1277 if (PyTuple_CheckExact(k)) {
1278 u = PyTuple_GET_ITEM(k, 1);
1279 Py_INCREF(u);
1280 Py_DECREF(k);
1281 }
1282 else {
1283 u = k;
1284 }
1285 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1286 i++;
1287 }
1288
1289 // Instead of rewriting o, we create new frozenset and embed in the
1290 // key tuple. Caller should get merged frozenset from the key tuple.
1291 PyObject *new = PyFrozenSet_New(tuple);
1292 Py_DECREF(tuple);
1293 if (new == NULL) {
1294 Py_DECREF(key);
1295 return NULL;
1296 }
1297 assert(PyTuple_GET_ITEM(key, 1) == o);
1298 Py_DECREF(o);
1299 PyTuple_SET_ITEM(key, 1, new);
1300 }
INADA Naokic2e16072018-11-26 21:23:22 +09001301
1302 return key;
1303}
1304
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001305static Py_ssize_t
1306compiler_add_const(struct compiler *c, PyObject *o)
1307{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001308 if (c->c_do_not_emit_bytecode) {
1309 return 0;
1310 }
1311
INADA Naokic2e16072018-11-26 21:23:22 +09001312 PyObject *key = merge_consts_recursive(c, o);
1313 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001314 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001315 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316
INADA Naokic2e16072018-11-26 21:23:22 +09001317 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1318 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
1322static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001323compiler_addop_load_const(struct compiler *c, PyObject *o)
1324{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001325 if (c->c_do_not_emit_bytecode) {
1326 return 1;
1327 }
1328
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001329 Py_ssize_t arg = compiler_add_const(c, o);
1330 if (arg < 0)
1331 return 0;
1332 return compiler_addop_i(c, LOAD_CONST, arg);
1333}
1334
1335static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001339 if (c->c_do_not_emit_bytecode) {
1340 return 1;
1341 }
1342
Victor Stinnerad9a0662013-11-19 22:23:20 +01001343 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 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
1349static int
1350compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001353 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001354
1355 if (c->c_do_not_emit_bytecode) {
1356 return 1;
1357 }
1358
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1360 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 arg = compiler_add_o(c, dict, mangled);
1363 Py_DECREF(mangled);
1364 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001365 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 return compiler_addop_i(c, opcode, arg);
1367}
1368
1369/* Add an opcode with an integer argument.
1370 Returns 0 on failure, 1 on success.
1371*/
1372
1373static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001374compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 struct instr *i;
1377 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001378
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001379 if (c->c_do_not_emit_bytecode) {
1380 return 1;
1381 }
1382
Victor Stinner2ad474b2016-03-01 23:34:47 +01001383 /* oparg value is unsigned, but a signed C int is usually used to store
1384 it in the C code (like Python/ceval.c).
1385
1386 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1387
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001388 The argument of a concrete bytecode instruction is limited to 8-bit.
1389 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1390 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001391 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 off = compiler_next_instr(c, c->u->u_curblock);
1394 if (off < 0)
1395 return 0;
1396 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001397 i->i_opcode = opcode;
1398 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 compiler_set_lineno(c, off);
1400 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401}
1402
1403static int
1404compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 struct instr *i;
1407 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001409 if (c->c_do_not_emit_bytecode) {
1410 return 1;
1411 }
1412
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001413 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 assert(b != NULL);
1415 off = compiler_next_instr(c, c->u->u_curblock);
1416 if (off < 0)
1417 return 0;
1418 i = &c->u->u_curblock->b_instr[off];
1419 i->i_opcode = opcode;
1420 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (absolute)
1422 i->i_jabs = 1;
1423 else
1424 i->i_jrel = 1;
1425 compiler_set_lineno(c, off);
1426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427}
1428
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001429/* NEXT_BLOCK() creates an implicit jump from the current block
1430 to the new block.
1431
1432 The returns inside this macro make it impossible to decref objects
1433 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (compiler_next_block((C)) == NULL) \
1437 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438}
1439
1440#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (!compiler_addop((C), (OP))) \
1442 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443}
1444
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001445#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_addop((C), (OP))) { \
1447 compiler_exit_scope(c); \
1448 return 0; \
1449 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001450}
1451
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001452#define ADDOP_LOAD_CONST(C, O) { \
1453 if (!compiler_addop_load_const((C), (O))) \
1454 return 0; \
1455}
1456
1457/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1458#define ADDOP_LOAD_CONST_NEW(C, O) { \
1459 PyObject *__new_const = (O); \
1460 if (__new_const == NULL) { \
1461 return 0; \
1462 } \
1463 if (!compiler_addop_load_const((C), __new_const)) { \
1464 Py_DECREF(__new_const); \
1465 return 0; \
1466 } \
1467 Py_DECREF(__new_const); \
1468}
1469
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1472 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473}
1474
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001475/* Same as ADDOP_O, but steals a reference. */
1476#define ADDOP_N(C, OP, O, TYPE) { \
1477 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1478 Py_DECREF((O)); \
1479 return 0; \
1480 } \
1481 Py_DECREF((O)); \
1482}
1483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1486 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (!compiler_addop_i((C), (OP), (O))) \
1491 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492}
1493
1494#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 if (!compiler_addop_j((C), (OP), (O), 1)) \
1496 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497}
1498
1499#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!compiler_addop_j((C), (OP), (O), 0)) \
1501 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502}
1503
1504/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1505 the ASDL name to synthesize the name of the C type and the visit function.
1506*/
1507
1508#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!compiler_visit_ ## TYPE((C), (V))) \
1510 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511}
1512
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001513#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (!compiler_visit_ ## TYPE((C), (V))) { \
1515 compiler_exit_scope(c); \
1516 return 0; \
1517 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001518}
1519
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!compiler_visit_slice((C), (V), (CTX))) \
1522 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523}
1524
1525#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 int _i; \
1527 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1528 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1529 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1530 if (!compiler_visit_ ## TYPE((C), elt)) \
1531 return 0; \
1532 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001535#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 int _i; \
1537 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1538 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1539 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1540 if (!compiler_visit_ ## TYPE((C), elt)) { \
1541 compiler_exit_scope(c); \
1542 return 0; \
1543 } \
1544 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001545}
1546
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001547/* These macros allows to check only for errors and not emmit bytecode
1548 * while visiting nodes.
1549*/
1550
1551#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1552 c->c_do_not_emit_bytecode++;
1553
1554#define END_DO_NOT_EMIT_BYTECODE \
1555 c->c_do_not_emit_bytecode--; \
1556}
1557
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001558/* Search if variable annotations are present statically in a block. */
1559
1560static int
1561find_ann(asdl_seq *stmts)
1562{
1563 int i, j, res = 0;
1564 stmt_ty st;
1565
1566 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1567 st = (stmt_ty)asdl_seq_GET(stmts, i);
1568 switch (st->kind) {
1569 case AnnAssign_kind:
1570 return 1;
1571 case For_kind:
1572 res = find_ann(st->v.For.body) ||
1573 find_ann(st->v.For.orelse);
1574 break;
1575 case AsyncFor_kind:
1576 res = find_ann(st->v.AsyncFor.body) ||
1577 find_ann(st->v.AsyncFor.orelse);
1578 break;
1579 case While_kind:
1580 res = find_ann(st->v.While.body) ||
1581 find_ann(st->v.While.orelse);
1582 break;
1583 case If_kind:
1584 res = find_ann(st->v.If.body) ||
1585 find_ann(st->v.If.orelse);
1586 break;
1587 case With_kind:
1588 res = find_ann(st->v.With.body);
1589 break;
1590 case AsyncWith_kind:
1591 res = find_ann(st->v.AsyncWith.body);
1592 break;
1593 case Try_kind:
1594 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1595 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1596 st->v.Try.handlers, j);
1597 if (find_ann(handler->v.ExceptHandler.body)) {
1598 return 1;
1599 }
1600 }
1601 res = find_ann(st->v.Try.body) ||
1602 find_ann(st->v.Try.finalbody) ||
1603 find_ann(st->v.Try.orelse);
1604 break;
1605 default:
1606 res = 0;
1607 }
1608 if (res) {
1609 break;
1610 }
1611 }
1612 return res;
1613}
1614
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001615/*
1616 * Frame block handling functions
1617 */
1618
1619static int
1620compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001621 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001622{
1623 struct fblockinfo *f;
1624 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1625 PyErr_SetString(PyExc_SyntaxError,
1626 "too many statically nested blocks");
1627 return 0;
1628 }
1629 f = &c->u->u_fblock[c->u->u_nfblocks++];
1630 f->fb_type = t;
1631 f->fb_block = b;
1632 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001633 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001634 return 1;
1635}
1636
1637static void
1638compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1639{
1640 struct compiler_unit *u = c->u;
1641 assert(u->u_nfblocks > 0);
1642 u->u_nfblocks--;
1643 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1644 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1645}
1646
Mark Shannonfee55262019-11-21 09:11:43 +00001647static int
1648compiler_call_exit_with_nones(struct compiler *c) {
1649 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1650 ADDOP(c, DUP_TOP);
1651 ADDOP(c, DUP_TOP);
1652 ADDOP_I(c, CALL_FUNCTION, 3);
1653 return 1;
1654}
1655
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001656/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001657 * popping the blocks will be restored afterwards, unless another
1658 * return, break or continue is found. In which case, the TOS will
1659 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660 */
1661static int
1662compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1663 int preserve_tos)
1664{
1665 switch (info->fb_type) {
1666 case WHILE_LOOP:
1667 return 1;
1668
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001669 case FOR_LOOP:
1670 /* Pop the iterator */
1671 if (preserve_tos) {
1672 ADDOP(c, ROT_TWO);
1673 }
1674 ADDOP(c, POP_TOP);
1675 return 1;
1676
1677 case EXCEPT:
1678 ADDOP(c, POP_BLOCK);
1679 return 1;
1680
1681 case FINALLY_TRY:
1682 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001683 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001684 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1685 return 0;
1686 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001687 }
Mark Shannonfee55262019-11-21 09:11:43 +00001688 VISIT_SEQ(c, stmt, info->fb_datum);
1689 if (preserve_tos) {
1690 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001691 }
1692 return 1;
Mark Shannonfee55262019-11-21 09:11:43 +00001693
1694 case FINALLY_END:
1695 if (preserve_tos) {
1696 ADDOP(c, ROT_FOUR);
1697 }
1698 ADDOP(c, POP_TOP);
1699 ADDOP(c, POP_TOP);
1700 ADDOP(c, POP_TOP);
1701 if (preserve_tos) {
1702 ADDOP(c, ROT_FOUR);
1703 }
1704 ADDOP(c, POP_EXCEPT);
1705 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 case WITH:
1708 case ASYNC_WITH:
1709 ADDOP(c, POP_BLOCK);
1710 if (preserve_tos) {
1711 ADDOP(c, ROT_TWO);
1712 }
Mark Shannonfee55262019-11-21 09:11:43 +00001713 if(!compiler_call_exit_with_nones(c)) {
1714 return 0;
1715 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001716 if (info->fb_type == ASYNC_WITH) {
1717 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001718 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001719 ADDOP(c, YIELD_FROM);
1720 }
Mark Shannonfee55262019-11-21 09:11:43 +00001721 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001722 return 1;
1723
1724 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001725 if (info->fb_datum) {
1726 ADDOP(c, POP_BLOCK);
1727 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001728 if (preserve_tos) {
1729 ADDOP(c, ROT_FOUR);
1730 }
Mark Shannonfee55262019-11-21 09:11:43 +00001731 ADDOP(c, POP_EXCEPT);
1732 if (info->fb_datum) {
1733 ADDOP_LOAD_CONST(c, Py_None);
1734 compiler_nameop(c, info->fb_datum, Store);
1735 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001736 }
Mark Shannonfee55262019-11-21 09:11:43 +00001737 return 1;
1738
1739 case POP_VALUE:
1740 if (preserve_tos) {
1741 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001742 }
Mark Shannonfee55262019-11-21 09:11:43 +00001743 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 return 1;
1745 }
1746 Py_UNREACHABLE();
1747}
1748
Mark Shannonfee55262019-11-21 09:11:43 +00001749/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1750static int
1751compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1752 if (c->u->u_nfblocks == 0) {
1753 return 1;
1754 }
1755 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1756 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1757 *loop = top;
1758 return 1;
1759 }
1760 struct fblockinfo copy = *top;
1761 c->u->u_nfblocks--;
1762 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1763 return 0;
1764 }
1765 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1766 return 0;
1767 }
1768 c->u->u_fblock[c->u->u_nfblocks] = copy;
1769 c->u->u_nfblocks++;
1770 return 1;
1771}
1772
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001773/* Compile a sequence of statements, checking for a docstring
1774 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775
1776static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001777compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001779 int i = 0;
1780 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001781 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001782
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001783 /* Set current line number to the line number of first statement.
1784 This way line number for SETUP_ANNOTATIONS will always
1785 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301786 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001787 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1788 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001789 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001790 c->u->u_lineno = st->lineno;
1791 }
1792 /* Every annotated class and module should have __annotations__. */
1793 if (find_ann(stmts)) {
1794 ADDOP(c, SETUP_ANNOTATIONS);
1795 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001796 if (!asdl_seq_LEN(stmts))
1797 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001798 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001799 if (c->c_optimize < 2) {
1800 docstring = _PyAST_GetDocString(stmts);
1801 if (docstring) {
1802 i = 1;
1803 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1804 assert(st->kind == Expr_kind);
1805 VISIT(c, expr, st->v.Expr.value);
1806 if (!compiler_nameop(c, __doc__, Store))
1807 return 0;
1808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001810 for (; i < asdl_seq_LEN(stmts); i++)
1811 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813}
1814
1815static PyCodeObject *
1816compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 PyCodeObject *co;
1819 int addNone = 1;
1820 static PyObject *module;
1821 if (!module) {
1822 module = PyUnicode_InternFromString("<module>");
1823 if (!module)
1824 return NULL;
1825 }
1826 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001827 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return NULL;
1829 switch (mod->kind) {
1830 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001831 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 compiler_exit_scope(c);
1833 return 0;
1834 }
1835 break;
1836 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001837 if (find_ann(mod->v.Interactive.body)) {
1838 ADDOP(c, SETUP_ANNOTATIONS);
1839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 c->c_interactive = 1;
1841 VISIT_SEQ_IN_SCOPE(c, stmt,
1842 mod->v.Interactive.body);
1843 break;
1844 case Expression_kind:
1845 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1846 addNone = 0;
1847 break;
1848 case Suite_kind:
1849 PyErr_SetString(PyExc_SystemError,
1850 "suite should not be possible");
1851 return 0;
1852 default:
1853 PyErr_Format(PyExc_SystemError,
1854 "module kind %d should not be possible",
1855 mod->kind);
1856 return 0;
1857 }
1858 co = assemble(c, addNone);
1859 compiler_exit_scope(c);
1860 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001861}
1862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863/* The test for LOCAL must come before the test for FREE in order to
1864 handle classes where name is both local and free. The local var is
1865 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001866*/
1867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868static int
1869get_ref_type(struct compiler *c, PyObject *name)
1870{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001871 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001872 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001873 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001875 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (scope == 0) {
1877 char buf[350];
1878 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001879 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001881 PyUnicode_AsUTF8(name),
1882 PyUnicode_AsUTF8(c->u->u_name),
1883 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 );
1888 Py_FatalError(buf);
1889 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892}
1893
1894static int
1895compiler_lookup_arg(PyObject *dict, PyObject *name)
1896{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001897 PyObject *v;
1898 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001900 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001901 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902}
1903
1904static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001907 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001908 if (qualname == NULL)
1909 qualname = co->co_name;
1910
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 if (free) {
1912 for (i = 0; i < free; ++i) {
1913 /* Bypass com_addop_varname because it will generate
1914 LOAD_DEREF but LOAD_CLOSURE is needed.
1915 */
1916 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1917 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001919 /* Special case: If a class contains a method with a
1920 free variable that has the same name as a method,
1921 the name will be considered free *and* local in the
1922 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001923 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 */
1925 reftype = get_ref_type(c, name);
1926 if (reftype == CELL)
1927 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1928 else /* (reftype == FREE) */
1929 arg = compiler_lookup_arg(c->u->u_freevars, name);
1930 if (arg == -1) {
1931 fprintf(stderr,
1932 "lookup %s in %s %d %d\n"
1933 "freevars of %s: %s\n",
1934 PyUnicode_AsUTF8(PyObject_Repr(name)),
1935 PyUnicode_AsUTF8(c->u->u_name),
1936 reftype, arg,
1937 PyUnicode_AsUTF8(co->co_name),
1938 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1939 Py_FatalError("compiler_make_closure()");
1940 }
1941 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001943 flags |= 0x08;
1944 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001946 ADDOP_LOAD_CONST(c, (PyObject*)co);
1947 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001948 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950}
1951
1952static int
1953compiler_decorators(struct compiler *c, asdl_seq* decos)
1954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (!decos)
1958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1961 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1962 }
1963 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964}
1965
1966static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001967compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001969{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001970 /* Push a dict of keyword-only default values.
1971
1972 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1973 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001974 int i;
1975 PyObject *keys = NULL;
1976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1978 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1979 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1980 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001981 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001982 if (!mangled) {
1983 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985 if (keys == NULL) {
1986 keys = PyList_New(1);
1987 if (keys == NULL) {
1988 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001989 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 }
1991 PyList_SET_ITEM(keys, 0, mangled);
1992 }
1993 else {
1994 int res = PyList_Append(keys, mangled);
1995 Py_DECREF(mangled);
1996 if (res == -1) {
1997 goto error;
1998 }
1999 }
2000 if (!compiler_visit_expr(c, default_)) {
2001 goto error;
2002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 }
2004 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 if (keys != NULL) {
2006 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2007 PyObject *keys_tuple = PyList_AsTuple(keys);
2008 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002009 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002010 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002011 assert(default_count > 0);
2012 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002013 }
2014 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002015 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002016 }
2017
2018error:
2019 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002020 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002021}
2022
2023static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002024compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2025{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002026 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002027 return 1;
2028}
2029
2030static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002031compiler_visit_argannotation(struct compiler *c, identifier id,
2032 expr_ty annotation, PyObject *names)
2033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002035 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002036 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2037 VISIT(c, annexpr, annotation)
2038 }
2039 else {
2040 VISIT(c, expr, annotation);
2041 }
Victor Stinner065efc32014-02-18 22:07:56 +01002042 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002043 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002044 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002045 if (PyList_Append(names, mangled) < 0) {
2046 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002047 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002048 }
2049 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002051 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002052}
2053
2054static int
2055compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2056 PyObject *names)
2057{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002058 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 for (i = 0; i < asdl_seq_LEN(args); i++) {
2060 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 c,
2063 arg->arg,
2064 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002065 names))
2066 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002068 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002069}
2070
2071static int
2072compiler_visit_annotations(struct compiler *c, arguments_ty args,
2073 expr_ty returns)
2074{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002075 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002076 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002077
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002078 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 */
2080 static identifier return_str;
2081 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002082 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 names = PyList_New(0);
2084 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002085 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002086
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002087 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002089 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2090 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002091 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002092 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002093 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002095 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002097 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002098 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002099 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (!return_str) {
2103 return_str = PyUnicode_InternFromString("return");
2104 if (!return_str)
2105 goto error;
2106 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002107 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 goto error;
2109 }
2110
2111 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002113 PyObject *keytuple = PyList_AsTuple(names);
2114 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002115 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002117 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002119 else {
2120 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002121 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002122 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002123
2124error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002126 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002127}
2128
2129static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002130compiler_visit_defaults(struct compiler *c, arguments_ty args)
2131{
2132 VISIT_SEQ(c, expr, args->defaults);
2133 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2134 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135}
2136
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002137static Py_ssize_t
2138compiler_default_arguments(struct compiler *c, arguments_ty args)
2139{
2140 Py_ssize_t funcflags = 0;
2141 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002142 if (!compiler_visit_defaults(c, args))
2143 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002144 funcflags |= 0x01;
2145 }
2146 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002147 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002148 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002149 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002150 return -1;
2151 }
2152 else if (res > 0) {
2153 funcflags |= 0x02;
2154 }
2155 }
2156 return funcflags;
2157}
2158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159static int
Yury Selivanov75445082015-05-11 22:57:16 -04002160compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002163 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002164 arguments_ty args;
2165 expr_ty returns;
2166 identifier name;
2167 asdl_seq* decos;
2168 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002169 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002170 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002171 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002172 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173
Yury Selivanov75445082015-05-11 22:57:16 -04002174 if (is_async) {
2175 assert(s->kind == AsyncFunctionDef_kind);
2176
2177 args = s->v.AsyncFunctionDef.args;
2178 returns = s->v.AsyncFunctionDef.returns;
2179 decos = s->v.AsyncFunctionDef.decorator_list;
2180 name = s->v.AsyncFunctionDef.name;
2181 body = s->v.AsyncFunctionDef.body;
2182
2183 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2184 } else {
2185 assert(s->kind == FunctionDef_kind);
2186
2187 args = s->v.FunctionDef.args;
2188 returns = s->v.FunctionDef.returns;
2189 decos = s->v.FunctionDef.decorator_list;
2190 name = s->v.FunctionDef.name;
2191 body = s->v.FunctionDef.body;
2192
2193 scope_type = COMPILER_SCOPE_FUNCTION;
2194 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (!compiler_decorators(c, decos))
2197 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002198
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002199 firstlineno = s->lineno;
2200 if (asdl_seq_LEN(decos)) {
2201 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2202 }
2203
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002204 funcflags = compiler_default_arguments(c, args);
2205 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002207 }
2208
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002209 annotations = compiler_visit_annotations(c, args, returns);
2210 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002211 return 0;
2212 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002213 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002214 funcflags |= 0x04;
2215 }
2216
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002217 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002218 return 0;
2219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220
INADA Naokicb41b272017-02-23 00:31:59 +09002221 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002222 if (c->c_optimize < 2) {
2223 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002224 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002225 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 compiler_exit_scope(c);
2227 return 0;
2228 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002231 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002233 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002235 qualname = c->u->u_qualname;
2236 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002238 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002239 Py_XDECREF(qualname);
2240 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002244 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002245 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* decorators */
2249 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2250 ADDOP_I(c, CALL_FUNCTION, 1);
2251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252
Yury Selivanov75445082015-05-11 22:57:16 -04002253 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254}
2255
2256static int
2257compiler_class(struct compiler *c, stmt_ty s)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyCodeObject *co;
2260 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002261 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (!compiler_decorators(c, decos))
2265 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002266
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002267 firstlineno = s->lineno;
2268 if (asdl_seq_LEN(decos)) {
2269 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2270 }
2271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 /* ultimately generate code for:
2273 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2274 where:
2275 <func> is a function/closure created from the class body;
2276 it has a single argument (__locals__) where the dict
2277 (or MutableSequence) representing the locals is passed
2278 <name> is the class name
2279 <bases> is the positional arguments and *varargs argument
2280 <keywords> is the keyword arguments and **kwds argument
2281 This borrows from compiler_call.
2282 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002285 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002286 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 return 0;
2288 /* this block represents what we do in the new scope */
2289 {
2290 /* use the class name for name mangling */
2291 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002292 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* load (global) __name__ ... */
2294 str = PyUnicode_InternFromString("__name__");
2295 if (!str || !compiler_nameop(c, str, Load)) {
2296 Py_XDECREF(str);
2297 compiler_exit_scope(c);
2298 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002299 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 Py_DECREF(str);
2301 /* ... and store it as __module__ */
2302 str = PyUnicode_InternFromString("__module__");
2303 if (!str || !compiler_nameop(c, str, Store)) {
2304 Py_XDECREF(str);
2305 compiler_exit_scope(c);
2306 return 0;
2307 }
2308 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002309 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002310 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002311 str = PyUnicode_InternFromString("__qualname__");
2312 if (!str || !compiler_nameop(c, str, Store)) {
2313 Py_XDECREF(str);
2314 compiler_exit_scope(c);
2315 return 0;
2316 }
2317 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002319 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 compiler_exit_scope(c);
2321 return 0;
2322 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002323 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002324 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002325 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002326 str = PyUnicode_InternFromString("__class__");
2327 if (str == NULL) {
2328 compiler_exit_scope(c);
2329 return 0;
2330 }
2331 i = compiler_lookup_arg(c->u->u_cellvars, str);
2332 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002333 if (i < 0) {
2334 compiler_exit_scope(c);
2335 return 0;
2336 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002337 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002340 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002341 str = PyUnicode_InternFromString("__classcell__");
2342 if (!str || !compiler_nameop(c, str, Store)) {
2343 Py_XDECREF(str);
2344 compiler_exit_scope(c);
2345 return 0;
2346 }
2347 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002349 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002350 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002351 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002352 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002353 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002354 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* create the code object */
2356 co = assemble(c, 1);
2357 }
2358 /* leave the new scope */
2359 compiler_exit_scope(c);
2360 if (co == NULL)
2361 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* 2. load the 'build_class' function */
2364 ADDOP(c, LOAD_BUILD_CLASS);
2365
2366 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002367 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_DECREF(co);
2369
2370 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002371 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372
2373 /* 5. generate the rest of the code for the call */
2374 if (!compiler_call_helper(c, 2,
2375 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002376 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return 0;
2378
2379 /* 6. apply decorators */
2380 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2381 ADDOP_I(c, CALL_FUNCTION, 1);
2382 }
2383
2384 /* 7. store into <name> */
2385 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2386 return 0;
2387 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388}
2389
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002390/* Return 0 if the expression is a constant value except named singletons.
2391 Return 1 otherwise. */
2392static int
2393check_is_arg(expr_ty e)
2394{
2395 if (e->kind != Constant_kind) {
2396 return 1;
2397 }
2398 PyObject *value = e->v.Constant.value;
2399 return (value == Py_None
2400 || value == Py_False
2401 || value == Py_True
2402 || value == Py_Ellipsis);
2403}
2404
2405/* Check operands of identity chacks ("is" and "is not").
2406 Emit a warning if any operand is a constant except named singletons.
2407 Return 0 on error.
2408 */
2409static int
2410check_compare(struct compiler *c, expr_ty e)
2411{
2412 Py_ssize_t i, n;
2413 int left = check_is_arg(e->v.Compare.left);
2414 n = asdl_seq_LEN(e->v.Compare.ops);
2415 for (i = 0; i < n; i++) {
2416 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2417 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2418 if (op == Is || op == IsNot) {
2419 if (!right || !left) {
2420 const char *msg = (op == Is)
2421 ? "\"is\" with a literal. Did you mean \"==\"?"
2422 : "\"is not\" with a literal. Did you mean \"!=\"?";
2423 return compiler_warn(c, msg);
2424 }
2425 }
2426 left = right;
2427 }
2428 return 1;
2429}
2430
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002432cmpop(cmpop_ty op)
2433{
2434 switch (op) {
2435 case Eq:
2436 return PyCmp_EQ;
2437 case NotEq:
2438 return PyCmp_NE;
2439 case Lt:
2440 return PyCmp_LT;
2441 case LtE:
2442 return PyCmp_LE;
2443 case Gt:
2444 return PyCmp_GT;
2445 case GtE:
2446 return PyCmp_GE;
2447 case Is:
2448 return PyCmp_IS;
2449 case IsNot:
2450 return PyCmp_IS_NOT;
2451 case In:
2452 return PyCmp_IN;
2453 case NotIn:
2454 return PyCmp_NOT_IN;
2455 default:
2456 return PyCmp_BAD;
2457 }
2458}
2459
2460static int
2461compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2462{
2463 switch (e->kind) {
2464 case UnaryOp_kind:
2465 if (e->v.UnaryOp.op == Not)
2466 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2467 /* fallback to general implementation */
2468 break;
2469 case BoolOp_kind: {
2470 asdl_seq *s = e->v.BoolOp.values;
2471 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2472 assert(n >= 0);
2473 int cond2 = e->v.BoolOp.op == Or;
2474 basicblock *next2 = next;
2475 if (!cond2 != !cond) {
2476 next2 = compiler_new_block(c);
2477 if (next2 == NULL)
2478 return 0;
2479 }
2480 for (i = 0; i < n; ++i) {
2481 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2482 return 0;
2483 }
2484 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2485 return 0;
2486 if (next2 != next)
2487 compiler_use_next_block(c, next2);
2488 return 1;
2489 }
2490 case IfExp_kind: {
2491 basicblock *end, *next2;
2492 end = compiler_new_block(c);
2493 if (end == NULL)
2494 return 0;
2495 next2 = compiler_new_block(c);
2496 if (next2 == NULL)
2497 return 0;
2498 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2499 return 0;
2500 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2501 return 0;
2502 ADDOP_JREL(c, JUMP_FORWARD, end);
2503 compiler_use_next_block(c, next2);
2504 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2505 return 0;
2506 compiler_use_next_block(c, end);
2507 return 1;
2508 }
2509 case Compare_kind: {
2510 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2511 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002512 if (!check_compare(c, e)) {
2513 return 0;
2514 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515 basicblock *cleanup = compiler_new_block(c);
2516 if (cleanup == NULL)
2517 return 0;
2518 VISIT(c, expr, e->v.Compare.left);
2519 for (i = 0; i < n; i++) {
2520 VISIT(c, expr,
2521 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2522 ADDOP(c, DUP_TOP);
2523 ADDOP(c, ROT_THREE);
2524 ADDOP_I(c, COMPARE_OP,
2525 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2526 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2527 NEXT_BLOCK(c);
2528 }
2529 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2530 ADDOP_I(c, COMPARE_OP,
2531 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2532 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2533 basicblock *end = compiler_new_block(c);
2534 if (end == NULL)
2535 return 0;
2536 ADDOP_JREL(c, JUMP_FORWARD, end);
2537 compiler_use_next_block(c, cleanup);
2538 ADDOP(c, POP_TOP);
2539 if (!cond) {
2540 ADDOP_JREL(c, JUMP_FORWARD, next);
2541 }
2542 compiler_use_next_block(c, end);
2543 return 1;
2544 }
2545 /* fallback to general implementation */
2546 break;
2547 }
2548 default:
2549 /* fallback to general implementation */
2550 break;
2551 }
2552
2553 /* general implementation */
2554 VISIT(c, expr, e);
2555 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2556 return 1;
2557}
2558
2559static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002560compiler_ifexp(struct compiler *c, expr_ty e)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 basicblock *end, *next;
2563
2564 assert(e->kind == IfExp_kind);
2565 end = compiler_new_block(c);
2566 if (end == NULL)
2567 return 0;
2568 next = compiler_new_block(c);
2569 if (next == NULL)
2570 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002571 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2572 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 VISIT(c, expr, e->v.IfExp.body);
2574 ADDOP_JREL(c, JUMP_FORWARD, end);
2575 compiler_use_next_block(c, next);
2576 VISIT(c, expr, e->v.IfExp.orelse);
2577 compiler_use_next_block(c, end);
2578 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002579}
2580
2581static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582compiler_lambda(struct compiler *c, expr_ty e)
2583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002585 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002587 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 arguments_ty args = e->v.Lambda.args;
2589 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (!name) {
2592 name = PyUnicode_InternFromString("<lambda>");
2593 if (!name)
2594 return 0;
2595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002597 funcflags = compiler_default_arguments(c, args);
2598 if (funcflags == -1) {
2599 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002601
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002602 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002603 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 /* Make None the first constant, so the lambda can't have a
2607 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002608 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002612 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2614 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2615 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002616 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 }
2618 else {
2619 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002620 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002622 qualname = c->u->u_qualname;
2623 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002625 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002628 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002629 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 Py_DECREF(co);
2631
2632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633}
2634
2635static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636compiler_if(struct compiler *c, stmt_ty s)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 basicblock *end, *next;
2639 int constant;
2640 assert(s->kind == If_kind);
2641 end = compiler_new_block(c);
2642 if (end == NULL)
2643 return 0;
2644
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002645 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002646 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 * constant = 1: "if 1", "if 2", ...
2648 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002649 if (constant == 0) {
2650 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002652 END_DO_NOT_EMIT_BYTECODE
2653 if (s->v.If.orelse) {
2654 VISIT_SEQ(c, stmt, s->v.If.orelse);
2655 }
2656 } else if (constant == 1) {
2657 VISIT_SEQ(c, stmt, s->v.If.body);
2658 if (s->v.If.orelse) {
2659 BEGIN_DO_NOT_EMIT_BYTECODE
2660 VISIT_SEQ(c, stmt, s->v.If.orelse);
2661 END_DO_NOT_EMIT_BYTECODE
2662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002664 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 next = compiler_new_block(c);
2666 if (next == NULL)
2667 return 0;
2668 }
Mark Shannonfee55262019-11-21 09:11:43 +00002669 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002671 }
2672 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002673 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002676 if (asdl_seq_LEN(s->v.If.orelse)) {
2677 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 compiler_use_next_block(c, next);
2679 VISIT_SEQ(c, stmt, s->v.If.orelse);
2680 }
2681 }
2682 compiler_use_next_block(c, end);
2683 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684}
2685
2686static int
2687compiler_for(struct compiler *c, stmt_ty s)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 start = compiler_new_block(c);
2692 cleanup = compiler_new_block(c);
2693 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002694 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002696 }
2697 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 VISIT(c, expr, s->v.For.iter);
2701 ADDOP(c, GET_ITER);
2702 compiler_use_next_block(c, start);
2703 ADDOP_JREL(c, FOR_ITER, cleanup);
2704 VISIT(c, expr, s->v.For.target);
2705 VISIT_SEQ(c, stmt, s->v.For.body);
2706 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2707 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002708
2709 compiler_pop_fblock(c, FOR_LOOP, start);
2710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 VISIT_SEQ(c, stmt, s->v.For.orelse);
2712 compiler_use_next_block(c, end);
2713 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714}
2715
Yury Selivanov75445082015-05-11 22:57:16 -04002716
2717static int
2718compiler_async_for(struct compiler *c, stmt_ty s)
2719{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002720 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002721 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2722 c->u->u_ste->ste_coroutine = 1;
2723 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002724 return compiler_error(c, "'async for' outside async function");
2725 }
2726
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002727 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002728 except = compiler_new_block(c);
2729 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002730
Mark Shannonfee55262019-11-21 09:11:43 +00002731 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002732 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002733 }
Yury Selivanov75445082015-05-11 22:57:16 -04002734 VISIT(c, expr, s->v.AsyncFor.iter);
2735 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002736
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002737 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002738 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002739 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002740 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002741 /* SETUP_FINALLY to guard the __anext__ call */
2742 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002743 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002744 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002745 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002746 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002747
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002748 /* Success block for __anext__ */
2749 VISIT(c, expr, s->v.AsyncFor.target);
2750 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2751 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2752
2753 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002754
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002755 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002756 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002757 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002758
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002759 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002760 VISIT_SEQ(c, stmt, s->v.For.orelse);
2761
2762 compiler_use_next_block(c, end);
2763
2764 return 1;
2765}
2766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767static int
2768compiler_while(struct compiler *c, stmt_ty s)
2769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002771 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002774 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002775 // Push a dummy block so the VISIT_SEQ knows that we are
2776 // inside a while loop so it can correctly evaluate syntax
2777 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002778 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002779 return 0;
2780 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002781 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002782 // Remove the dummy block now that is not needed.
2783 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002784 END_DO_NOT_EMIT_BYTECODE
2785 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return 1;
2789 }
2790 loop = compiler_new_block(c);
2791 end = compiler_new_block(c);
2792 if (constant == -1) {
2793 anchor = compiler_new_block(c);
2794 if (anchor == NULL)
2795 return 0;
2796 }
2797 if (loop == NULL || end == NULL)
2798 return 0;
2799 if (s->v.While.orelse) {
2800 orelse = compiler_new_block(c);
2801 if (orelse == NULL)
2802 return 0;
2803 }
2804 else
2805 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002808 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 return 0;
2810 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002811 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2812 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 }
2814 VISIT_SEQ(c, stmt, s->v.While.body);
2815 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 /* XXX should the two POP instructions be in a separate block
2818 if there is no else clause ?
2819 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002821 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002823 compiler_pop_fblock(c, WHILE_LOOP, loop);
2824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 if (orelse != NULL) /* what if orelse is just pass? */
2826 VISIT_SEQ(c, stmt, s->v.While.orelse);
2827 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830}
2831
2832static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002833compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002835 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002836 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002837 if (c->u->u_ste->ste_type != FunctionBlock)
2838 return compiler_error(c, "'return' outside function");
2839 if (s->v.Return.value != NULL &&
2840 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2841 {
2842 return compiler_error(
2843 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 if (preserve_tos) {
2846 VISIT(c, expr, s->v.Return.value);
2847 }
Mark Shannonfee55262019-11-21 09:11:43 +00002848 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2849 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002851 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002852 }
2853 else if (!preserve_tos) {
2854 VISIT(c, expr, s->v.Return.value);
2855 }
2856 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
2860
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002861static int
2862compiler_break(struct compiler *c)
2863{
Mark Shannonfee55262019-11-21 09:11:43 +00002864 struct fblockinfo *loop = NULL;
2865 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2866 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002867 }
Mark Shannonfee55262019-11-21 09:11:43 +00002868 if (loop == NULL) {
2869 return compiler_error(c, "'break' outside loop");
2870 }
2871 if (!compiler_unwind_fblock(c, loop, 0)) {
2872 return 0;
2873 }
2874 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2875 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002876}
2877
2878static int
2879compiler_continue(struct compiler *c)
2880{
Mark Shannonfee55262019-11-21 09:11:43 +00002881 struct fblockinfo *loop = NULL;
2882 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2883 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884 }
Mark Shannonfee55262019-11-21 09:11:43 +00002885 if (loop == NULL) {
2886 return compiler_error(c, "'continue' not properly in loop");
2887 }
2888 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2889 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890}
2891
2892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894
2895 SETUP_FINALLY L
2896 <code for body>
2897 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002898 <code for finalbody>
2899 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002900 L:
2901 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002902 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 The special instructions use the block stack. Each block
2905 stack entry contains the instruction that created it (here
2906 SETUP_FINALLY), the level of the value stack at the time the
2907 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 Pushes the current value stack level and the label
2911 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002913 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916 when a SETUP_FINALLY entry is found, the raised and the caught
2917 exceptions are pushed onto the value stack (and the exception
2918 condition is cleared), and the interpreter jumps to the label
2919 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920*/
2921
2922static int
2923compiler_try_finally(struct compiler *c, stmt_ty s)
2924{
Mark Shannonfee55262019-11-21 09:11:43 +00002925 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 body = compiler_new_block(c);
2928 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002929 exit = compiler_new_block(c);
2930 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002933 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 ADDOP_JREL(c, SETUP_FINALLY, end);
2935 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002936 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002938 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2939 if (!compiler_try_except(c, s))
2940 return 0;
2941 }
2942 else {
2943 VISIT_SEQ(c, stmt, s->v.Try.body);
2944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002946 compiler_pop_fblock(c, FINALLY_TRY, body);
2947 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2948 ADDOP_JREL(c, JUMP_FORWARD, exit);
2949 /* `finally` block */
2950 compiler_use_next_block(c, end);
2951 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2952 return 0;
2953 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2954 compiler_pop_fblock(c, FINALLY_END, end);
2955 ADDOP(c, RERAISE);
2956 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958}
2959
2960/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002961 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 (The contents of the value stack is shown in [], with the top
2963 at the right; 'tb' is trace-back info, 'val' the exception's
2964 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
2966 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002967 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 [] <code for S>
2969 [] POP_BLOCK
2970 [] JUMP_FORWARD L0
2971
2972 [tb, val, exc] L1: DUP )
2973 [tb, val, exc, exc] <evaluate E1> )
2974 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2975 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2976 [tb, val, exc] POP
2977 [tb, val] <assign to V1> (or POP if no V1)
2978 [tb] POP
2979 [] <code for S1>
2980 JUMP_FORWARD L0
2981
2982 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983 .............................etc.......................
2984
Mark Shannonfee55262019-11-21 09:11:43 +00002985 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986
2987 [] L0: <next statement>
2988
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 Of course, parts are not generated if Vi or Ei is not present.
2990*/
2991static int
2992compiler_try_except(struct compiler *c, stmt_ty s)
2993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002995 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 body = compiler_new_block(c);
2998 except = compiler_new_block(c);
2999 orelse = compiler_new_block(c);
3000 end = compiler_new_block(c);
3001 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3002 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003003 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003005 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003007 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 ADDOP(c, POP_BLOCK);
3009 compiler_pop_fblock(c, EXCEPT, body);
3010 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003011 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 compiler_use_next_block(c, except);
3013 for (i = 0; i < n; i++) {
3014 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003015 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 if (!handler->v.ExceptHandler.type && i < n-1)
3017 return compiler_error(c, "default 'except:' must be last");
3018 c->u->u_lineno_set = 0;
3019 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003020 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 except = compiler_new_block(c);
3022 if (except == NULL)
3023 return 0;
3024 if (handler->v.ExceptHandler.type) {
3025 ADDOP(c, DUP_TOP);
3026 VISIT(c, expr, handler->v.ExceptHandler.type);
3027 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3028 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3029 }
3030 ADDOP(c, POP_TOP);
3031 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003032 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003033
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003034 cleanup_end = compiler_new_block(c);
3035 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003036 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003037 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003038 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003039
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003040 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3041 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003043 /*
3044 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003045 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003046 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003047 try:
3048 # body
3049 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003050 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003051 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003052 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003054 /* second try: */
3055 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3056 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003057 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003060 /* second # body */
3061 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003062 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003063 ADDOP(c, POP_BLOCK);
3064 ADDOP(c, POP_EXCEPT);
3065 /* name = None; del name */
3066 ADDOP_LOAD_CONST(c, Py_None);
3067 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3068 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3069 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070
Mark Shannonfee55262019-11-21 09:11:43 +00003071 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003074 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003075 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078
Mark Shannonfee55262019-11-21 09:11:43 +00003079 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 }
3081 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003085 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087
Guido van Rossumb940e112007-01-10 16:19:56 +00003088 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 ADDOP(c, POP_TOP);
3090 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003091 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003092 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003094 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003095 ADDOP(c, POP_EXCEPT);
3096 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 compiler_use_next_block(c, except);
3099 }
Mark Shannonfee55262019-11-21 09:11:43 +00003100 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003102 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 compiler_use_next_block(c, end);
3104 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105}
3106
3107static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003108compiler_try(struct compiler *c, stmt_ty s) {
3109 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3110 return compiler_try_finally(c, s);
3111 else
3112 return compiler_try_except(c, s);
3113}
3114
3115
3116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117compiler_import_as(struct compiler *c, identifier name, identifier asname)
3118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 /* The IMPORT_NAME opcode was already generated. This function
3120 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003123 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003125 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3126 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003127 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003128 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003129 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003131 while (1) {
3132 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003134 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003135 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003136 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003137 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003139 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003140 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003141 if (dot == -1) {
3142 break;
3143 }
3144 ADDOP(c, ROT_TWO);
3145 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003147 if (!compiler_nameop(c, asname, Store)) {
3148 return 0;
3149 }
3150 ADDOP(c, POP_TOP);
3151 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 }
3153 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154}
3155
3156static int
3157compiler_import(struct compiler *c, stmt_ty s)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* The Import node stores a module name like a.b.c as a single
3160 string. This is convenient for all cases except
3161 import a.b.c as d
3162 where we need to parse that string to extract the individual
3163 module names.
3164 XXX Perhaps change the representation to make this case simpler?
3165 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003166 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 for (i = 0; i < n; i++) {
3169 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3170 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003172 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3173 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 if (alias->asname) {
3177 r = compiler_import_as(c, alias->name, alias->asname);
3178 if (!r)
3179 return r;
3180 }
3181 else {
3182 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003183 Py_ssize_t dot = PyUnicode_FindChar(
3184 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003185 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003186 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003187 if (tmp == NULL)
3188 return 0;
3189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003191 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 Py_DECREF(tmp);
3193 }
3194 if (!r)
3195 return r;
3196 }
3197 }
3198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199}
3200
3201static int
3202compiler_from_import(struct compiler *c, stmt_ty s)
3203{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003204 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003205 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 if (!empty_string) {
3209 empty_string = PyUnicode_FromString("");
3210 if (!empty_string)
3211 return 0;
3212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003214 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003215
3216 names = PyTuple_New(n);
3217 if (!names)
3218 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 /* build up the names */
3221 for (i = 0; i < n; i++) {
3222 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3223 Py_INCREF(alias->name);
3224 PyTuple_SET_ITEM(names, i, alias->name);
3225 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003228 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 Py_DECREF(names);
3230 return compiler_error(c, "from __future__ imports must occur "
3231 "at the beginning of the file");
3232 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003233 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 if (s->v.ImportFrom.module) {
3236 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3237 }
3238 else {
3239 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3240 }
3241 for (i = 0; i < n; i++) {
3242 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3243 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003245 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 assert(n == 1);
3247 ADDOP(c, IMPORT_STAR);
3248 return 1;
3249 }
3250
3251 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3252 store_name = alias->name;
3253 if (alias->asname)
3254 store_name = alias->asname;
3255
3256 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 return 0;
3258 }
3259 }
3260 /* remove imported module */
3261 ADDOP(c, POP_TOP);
3262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263}
3264
3265static int
3266compiler_assert(struct compiler *c, stmt_ty s)
3267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Georg Brandl8334fd92010-12-04 10:26:46 +00003270 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003273 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3274 {
3275 if (!compiler_warn(c, "assertion is always true, "
3276 "perhaps remove parentheses?"))
3277 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003278 return 0;
3279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 end = compiler_new_block(c);
3282 if (end == NULL)
3283 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003284 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3285 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003286 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 if (s->v.Assert.msg) {
3288 VISIT(c, expr, s->v.Assert.msg);
3289 ADDOP_I(c, CALL_FUNCTION, 1);
3290 }
3291 ADDOP_I(c, RAISE_VARARGS, 1);
3292 compiler_use_next_block(c, end);
3293 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294}
3295
3296static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003297compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3298{
3299 if (c->c_interactive && c->c_nestlevel <= 1) {
3300 VISIT(c, expr, value);
3301 ADDOP(c, PRINT_EXPR);
3302 return 1;
3303 }
3304
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003305 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003306 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003307 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003308 }
3309
3310 VISIT(c, expr, value);
3311 ADDOP(c, POP_TOP);
3312 return 1;
3313}
3314
3315static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316compiler_visit_stmt(struct compiler *c, stmt_ty s)
3317{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003318 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 /* Always assign a lineno to the next instruction for a stmt. */
3321 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003322 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 switch (s->kind) {
3326 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003327 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 case ClassDef_kind:
3329 return compiler_class(c, s);
3330 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003331 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 case Delete_kind:
3333 VISIT_SEQ(c, expr, s->v.Delete.targets)
3334 break;
3335 case Assign_kind:
3336 n = asdl_seq_LEN(s->v.Assign.targets);
3337 VISIT(c, expr, s->v.Assign.value);
3338 for (i = 0; i < n; i++) {
3339 if (i < n - 1)
3340 ADDOP(c, DUP_TOP);
3341 VISIT(c, expr,
3342 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3343 }
3344 break;
3345 case AugAssign_kind:
3346 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003347 case AnnAssign_kind:
3348 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 case For_kind:
3350 return compiler_for(c, s);
3351 case While_kind:
3352 return compiler_while(c, s);
3353 case If_kind:
3354 return compiler_if(c, s);
3355 case Raise_kind:
3356 n = 0;
3357 if (s->v.Raise.exc) {
3358 VISIT(c, expr, s->v.Raise.exc);
3359 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003360 if (s->v.Raise.cause) {
3361 VISIT(c, expr, s->v.Raise.cause);
3362 n++;
3363 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003365 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003367 case Try_kind:
3368 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 case Assert_kind:
3370 return compiler_assert(c, s);
3371 case Import_kind:
3372 return compiler_import(c, s);
3373 case ImportFrom_kind:
3374 return compiler_from_import(c, s);
3375 case Global_kind:
3376 case Nonlocal_kind:
3377 break;
3378 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003379 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 case Pass_kind:
3381 break;
3382 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003383 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 case Continue_kind:
3385 return compiler_continue(c);
3386 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003387 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003388 case AsyncFunctionDef_kind:
3389 return compiler_function(c, s, 1);
3390 case AsyncWith_kind:
3391 return compiler_async_with(c, s, 0);
3392 case AsyncFor_kind:
3393 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 }
Yury Selivanov75445082015-05-11 22:57:16 -04003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397}
3398
3399static int
3400unaryop(unaryop_ty op)
3401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 switch (op) {
3403 case Invert:
3404 return UNARY_INVERT;
3405 case Not:
3406 return UNARY_NOT;
3407 case UAdd:
3408 return UNARY_POSITIVE;
3409 case USub:
3410 return UNARY_NEGATIVE;
3411 default:
3412 PyErr_Format(PyExc_SystemError,
3413 "unary op %d should not be possible", op);
3414 return 0;
3415 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003416}
3417
3418static int
3419binop(struct compiler *c, operator_ty op)
3420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 switch (op) {
3422 case Add:
3423 return BINARY_ADD;
3424 case Sub:
3425 return BINARY_SUBTRACT;
3426 case Mult:
3427 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003428 case MatMult:
3429 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 case Div:
3431 return BINARY_TRUE_DIVIDE;
3432 case Mod:
3433 return BINARY_MODULO;
3434 case Pow:
3435 return BINARY_POWER;
3436 case LShift:
3437 return BINARY_LSHIFT;
3438 case RShift:
3439 return BINARY_RSHIFT;
3440 case BitOr:
3441 return BINARY_OR;
3442 case BitXor:
3443 return BINARY_XOR;
3444 case BitAnd:
3445 return BINARY_AND;
3446 case FloorDiv:
3447 return BINARY_FLOOR_DIVIDE;
3448 default:
3449 PyErr_Format(PyExc_SystemError,
3450 "binary op %d should not be possible", op);
3451 return 0;
3452 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453}
3454
3455static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456inplace_binop(struct compiler *c, operator_ty op)
3457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 switch (op) {
3459 case Add:
3460 return INPLACE_ADD;
3461 case Sub:
3462 return INPLACE_SUBTRACT;
3463 case Mult:
3464 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003465 case MatMult:
3466 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 case Div:
3468 return INPLACE_TRUE_DIVIDE;
3469 case Mod:
3470 return INPLACE_MODULO;
3471 case Pow:
3472 return INPLACE_POWER;
3473 case LShift:
3474 return INPLACE_LSHIFT;
3475 case RShift:
3476 return INPLACE_RSHIFT;
3477 case BitOr:
3478 return INPLACE_OR;
3479 case BitXor:
3480 return INPLACE_XOR;
3481 case BitAnd:
3482 return INPLACE_AND;
3483 case FloorDiv:
3484 return INPLACE_FLOOR_DIVIDE;
3485 default:
3486 PyErr_Format(PyExc_SystemError,
3487 "inplace binary op %d should not be possible", op);
3488 return 0;
3489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490}
3491
3492static int
3493compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3494{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003495 int op, scope;
3496 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 PyObject *dict = c->u->u_names;
3500 PyObject *mangled;
3501 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003503 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3504 !_PyUnicode_EqualToASCIIString(name, "True") &&
3505 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003506
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003507 mangled = _Py_Mangle(c->u->u_private, name);
3508 if (!mangled)
3509 return 0;
3510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 op = 0;
3512 optype = OP_NAME;
3513 scope = PyST_GetScope(c->u->u_ste, mangled);
3514 switch (scope) {
3515 case FREE:
3516 dict = c->u->u_freevars;
3517 optype = OP_DEREF;
3518 break;
3519 case CELL:
3520 dict = c->u->u_cellvars;
3521 optype = OP_DEREF;
3522 break;
3523 case LOCAL:
3524 if (c->u->u_ste->ste_type == FunctionBlock)
3525 optype = OP_FAST;
3526 break;
3527 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003528 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 optype = OP_GLOBAL;
3530 break;
3531 case GLOBAL_EXPLICIT:
3532 optype = OP_GLOBAL;
3533 break;
3534 default:
3535 /* scope can be 0 */
3536 break;
3537 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003540 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 switch (optype) {
3543 case OP_DEREF:
3544 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003545 case Load:
3546 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3547 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003548 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003549 op = STORE_DEREF;
3550 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 case AugLoad:
3552 case AugStore:
3553 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003554 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 case Param:
3556 default:
3557 PyErr_SetString(PyExc_SystemError,
3558 "param invalid for deref variable");
3559 return 0;
3560 }
3561 break;
3562 case OP_FAST:
3563 switch (ctx) {
3564 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003565 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003566 op = STORE_FAST;
3567 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 case Del: op = DELETE_FAST; break;
3569 case AugLoad:
3570 case AugStore:
3571 break;
3572 case Param:
3573 default:
3574 PyErr_SetString(PyExc_SystemError,
3575 "param invalid for local variable");
3576 return 0;
3577 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003578 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 return 1;
3580 case OP_GLOBAL:
3581 switch (ctx) {
3582 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003583 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003584 op = STORE_GLOBAL;
3585 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 case Del: op = DELETE_GLOBAL; break;
3587 case AugLoad:
3588 case AugStore:
3589 break;
3590 case Param:
3591 default:
3592 PyErr_SetString(PyExc_SystemError,
3593 "param invalid for global variable");
3594 return 0;
3595 }
3596 break;
3597 case OP_NAME:
3598 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003599 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003600 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003601 op = STORE_NAME;
3602 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 case Del: op = DELETE_NAME; break;
3604 case AugLoad:
3605 case AugStore:
3606 break;
3607 case Param:
3608 default:
3609 PyErr_SetString(PyExc_SystemError,
3610 "param invalid for name variable");
3611 return 0;
3612 }
3613 break;
3614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 assert(op);
3617 arg = compiler_add_o(c, dict, mangled);
3618 Py_DECREF(mangled);
3619 if (arg < 0)
3620 return 0;
3621 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622}
3623
3624static int
3625compiler_boolop(struct compiler *c, expr_ty e)
3626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003628 int jumpi;
3629 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 assert(e->kind == BoolOp_kind);
3633 if (e->v.BoolOp.op == And)
3634 jumpi = JUMP_IF_FALSE_OR_POP;
3635 else
3636 jumpi = JUMP_IF_TRUE_OR_POP;
3637 end = compiler_new_block(c);
3638 if (end == NULL)
3639 return 0;
3640 s = e->v.BoolOp.values;
3641 n = asdl_seq_LEN(s) - 1;
3642 assert(n >= 0);
3643 for (i = 0; i < n; ++i) {
3644 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3645 ADDOP_JABS(c, jumpi, end);
3646 }
3647 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3648 compiler_use_next_block(c, end);
3649 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650}
3651
3652static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003653starunpack_helper(struct compiler *c, asdl_seq *elts,
3654 int single_op, int inner_op, int outer_op)
3655{
3656 Py_ssize_t n = asdl_seq_LEN(elts);
3657 Py_ssize_t i, nsubitems = 0, nseen = 0;
3658 for (i = 0; i < n; i++) {
3659 expr_ty elt = asdl_seq_GET(elts, i);
3660 if (elt->kind == Starred_kind) {
3661 if (nseen) {
3662 ADDOP_I(c, inner_op, nseen);
3663 nseen = 0;
3664 nsubitems++;
3665 }
3666 VISIT(c, expr, elt->v.Starred.value);
3667 nsubitems++;
3668 }
3669 else {
3670 VISIT(c, expr, elt);
3671 nseen++;
3672 }
3673 }
3674 if (nsubitems) {
3675 if (nseen) {
3676 ADDOP_I(c, inner_op, nseen);
3677 nsubitems++;
3678 }
3679 ADDOP_I(c, outer_op, nsubitems);
3680 }
3681 else
3682 ADDOP_I(c, single_op, nseen);
3683 return 1;
3684}
3685
3686static int
3687assignment_helper(struct compiler *c, asdl_seq *elts)
3688{
3689 Py_ssize_t n = asdl_seq_LEN(elts);
3690 Py_ssize_t i;
3691 int seen_star = 0;
3692 for (i = 0; i < n; i++) {
3693 expr_ty elt = asdl_seq_GET(elts, i);
3694 if (elt->kind == Starred_kind && !seen_star) {
3695 if ((i >= (1 << 8)) ||
3696 (n-i-1 >= (INT_MAX >> 8)))
3697 return compiler_error(c,
3698 "too many expressions in "
3699 "star-unpacking assignment");
3700 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3701 seen_star = 1;
3702 asdl_seq_SET(elts, i, elt->v.Starred.value);
3703 }
3704 else if (elt->kind == Starred_kind) {
3705 return compiler_error(c,
3706 "two starred expressions in assignment");
3707 }
3708 }
3709 if (!seen_star) {
3710 ADDOP_I(c, UNPACK_SEQUENCE, n);
3711 }
3712 VISIT_SEQ(c, expr, elts);
3713 return 1;
3714}
3715
3716static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717compiler_list(struct compiler *c, expr_ty e)
3718{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003719 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003720 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003723 else if (e->v.List.ctx == Load) {
3724 return starunpack_helper(c, elts,
3725 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 else
3728 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003730}
3731
3732static int
3733compiler_tuple(struct compiler *c, expr_ty e)
3734{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003736 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 return assignment_helper(c, elts);
3738 }
3739 else if (e->v.Tuple.ctx == Load) {
3740 return starunpack_helper(c, elts,
3741 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3742 }
3743 else
3744 VISIT_SEQ(c, expr, elts);
3745 return 1;
3746}
3747
3748static int
3749compiler_set(struct compiler *c, expr_ty e)
3750{
3751 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3752 BUILD_SET, BUILD_SET_UNPACK);
3753}
3754
3755static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003756are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3757{
3758 Py_ssize_t i;
3759 for (i = begin; i < end; i++) {
3760 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003761 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003762 return 0;
3763 }
3764 return 1;
3765}
3766
3767static int
3768compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3769{
3770 Py_ssize_t i, n = end - begin;
3771 PyObject *keys, *key;
3772 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3773 for (i = begin; i < end; i++) {
3774 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3775 }
3776 keys = PyTuple_New(n);
3777 if (keys == NULL) {
3778 return 0;
3779 }
3780 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003781 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003782 Py_INCREF(key);
3783 PyTuple_SET_ITEM(keys, i - begin, key);
3784 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003785 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003786 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3787 }
3788 else {
3789 for (i = begin; i < end; i++) {
3790 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3791 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3792 }
3793 ADDOP_I(c, BUILD_MAP, n);
3794 }
3795 return 1;
3796}
3797
3798static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799compiler_dict(struct compiler *c, expr_ty e)
3800{
Victor Stinner976bb402016-03-23 11:36:19 +01003801 Py_ssize_t i, n, elements;
3802 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 int is_unpacking = 0;
3804 n = asdl_seq_LEN(e->v.Dict.values);
3805 containers = 0;
3806 elements = 0;
3807 for (i = 0; i < n; i++) {
3808 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3809 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003810 if (!compiler_subdict(c, e, i - elements, i))
3811 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003812 containers++;
3813 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003815 if (is_unpacking) {
3816 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3817 containers++;
3818 }
3819 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003820 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 }
3822 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003823 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003824 if (!compiler_subdict(c, e, n - elements, n))
3825 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003826 containers++;
3827 }
3828 /* If there is more than one dict, they need to be merged into a new
3829 * dict. If there is one dict and it's an unpacking, then it needs
3830 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003831 if (containers > 1 || is_unpacking) {
3832 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 }
3834 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835}
3836
3837static int
3838compiler_compare(struct compiler *c, expr_ty e)
3839{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003840 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003842 if (!check_compare(c, e)) {
3843 return 0;
3844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003846 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3847 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3848 if (n == 0) {
3849 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3850 ADDOP_I(c, COMPARE_OP,
3851 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3852 }
3853 else {
3854 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 if (cleanup == NULL)
3856 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003857 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 VISIT(c, expr,
3859 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003860 ADDOP(c, DUP_TOP);
3861 ADDOP(c, ROT_THREE);
3862 ADDOP_I(c, COMPARE_OP,
3863 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3864 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3865 NEXT_BLOCK(c);
3866 }
3867 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3868 ADDOP_I(c, COMPARE_OP,
3869 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 basicblock *end = compiler_new_block(c);
3871 if (end == NULL)
3872 return 0;
3873 ADDOP_JREL(c, JUMP_FORWARD, end);
3874 compiler_use_next_block(c, cleanup);
3875 ADDOP(c, ROT_TWO);
3876 ADDOP(c, POP_TOP);
3877 compiler_use_next_block(c, end);
3878 }
3879 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880}
3881
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003882static PyTypeObject *
3883infer_type(expr_ty e)
3884{
3885 switch (e->kind) {
3886 case Tuple_kind:
3887 return &PyTuple_Type;
3888 case List_kind:
3889 case ListComp_kind:
3890 return &PyList_Type;
3891 case Dict_kind:
3892 case DictComp_kind:
3893 return &PyDict_Type;
3894 case Set_kind:
3895 case SetComp_kind:
3896 return &PySet_Type;
3897 case GeneratorExp_kind:
3898 return &PyGen_Type;
3899 case Lambda_kind:
3900 return &PyFunction_Type;
3901 case JoinedStr_kind:
3902 case FormattedValue_kind:
3903 return &PyUnicode_Type;
3904 case Constant_kind:
3905 return e->v.Constant.value->ob_type;
3906 default:
3907 return NULL;
3908 }
3909}
3910
3911static int
3912check_caller(struct compiler *c, expr_ty e)
3913{
3914 switch (e->kind) {
3915 case Constant_kind:
3916 case Tuple_kind:
3917 case List_kind:
3918 case ListComp_kind:
3919 case Dict_kind:
3920 case DictComp_kind:
3921 case Set_kind:
3922 case SetComp_kind:
3923 case GeneratorExp_kind:
3924 case JoinedStr_kind:
3925 case FormattedValue_kind:
3926 return compiler_warn(c, "'%.200s' object is not callable; "
3927 "perhaps you missed a comma?",
3928 infer_type(e)->tp_name);
3929 default:
3930 return 1;
3931 }
3932}
3933
3934static int
3935check_subscripter(struct compiler *c, expr_ty e)
3936{
3937 PyObject *v;
3938
3939 switch (e->kind) {
3940 case Constant_kind:
3941 v = e->v.Constant.value;
3942 if (!(v == Py_None || v == Py_Ellipsis ||
3943 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3944 PyAnySet_Check(v)))
3945 {
3946 return 1;
3947 }
3948 /* fall through */
3949 case Set_kind:
3950 case SetComp_kind:
3951 case GeneratorExp_kind:
3952 case Lambda_kind:
3953 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3954 "perhaps you missed a comma?",
3955 infer_type(e)->tp_name);
3956 default:
3957 return 1;
3958 }
3959}
3960
3961static int
3962check_index(struct compiler *c, expr_ty e, slice_ty s)
3963{
3964 PyObject *v;
3965
3966 if (s->kind != Index_kind) {
3967 return 1;
3968 }
3969 PyTypeObject *index_type = infer_type(s->v.Index.value);
3970 if (index_type == NULL
3971 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3972 || index_type == &PySlice_Type) {
3973 return 1;
3974 }
3975
3976 switch (e->kind) {
3977 case Constant_kind:
3978 v = e->v.Constant.value;
3979 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3980 return 1;
3981 }
3982 /* fall through */
3983 case Tuple_kind:
3984 case List_kind:
3985 case ListComp_kind:
3986 case JoinedStr_kind:
3987 case FormattedValue_kind:
3988 return compiler_warn(c, "%.200s indices must be integers or slices, "
3989 "not %.200s; "
3990 "perhaps you missed a comma?",
3991 infer_type(e)->tp_name,
3992 index_type->tp_name);
3993 default:
3994 return 1;
3995 }
3996}
3997
Zackery Spytz97f5de02019-03-22 01:30:32 -06003998// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003999static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004000maybe_optimize_method_call(struct compiler *c, expr_ty e)
4001{
4002 Py_ssize_t argsl, i;
4003 expr_ty meth = e->v.Call.func;
4004 asdl_seq *args = e->v.Call.args;
4005
4006 /* Check that the call node is an attribute access, and that
4007 the call doesn't have keyword parameters. */
4008 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4009 asdl_seq_LEN(e->v.Call.keywords))
4010 return -1;
4011
4012 /* Check that there are no *varargs types of arguments. */
4013 argsl = asdl_seq_LEN(args);
4014 for (i = 0; i < argsl; i++) {
4015 expr_ty elt = asdl_seq_GET(args, i);
4016 if (elt->kind == Starred_kind) {
4017 return -1;
4018 }
4019 }
4020
4021 /* Alright, we can optimize the code. */
4022 VISIT(c, expr, meth->v.Attribute.value);
4023 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4024 VISIT_SEQ(c, expr, e->v.Call.args);
4025 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4026 return 1;
4027}
4028
4029static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030compiler_call(struct compiler *c, expr_ty e)
4031{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004032 int ret = maybe_optimize_method_call(c, e);
4033 if (ret >= 0) {
4034 return ret;
4035 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004036 if (!check_caller(c, e->v.Call.func)) {
4037 return 0;
4038 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 VISIT(c, expr, e->v.Call.func);
4040 return compiler_call_helper(c, 0,
4041 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004042 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004043}
4044
Eric V. Smith235a6f02015-09-19 14:51:32 -04004045static int
4046compiler_joined_str(struct compiler *c, expr_ty e)
4047{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004048 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004049 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4050 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004051 return 1;
4052}
4053
Eric V. Smitha78c7952015-11-03 12:45:05 -05004054/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004055static int
4056compiler_formatted_value(struct compiler *c, expr_ty e)
4057{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004058 /* Our oparg encodes 2 pieces of information: the conversion
4059 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004060
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004061 Convert the conversion char to 3 bits:
4062 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004063 !s : 001 0x1 FVC_STR
4064 !r : 010 0x2 FVC_REPR
4065 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004066
Eric V. Smitha78c7952015-11-03 12:45:05 -05004067 next bit is whether or not we have a format spec:
4068 yes : 100 0x4
4069 no : 000 0x0
4070 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004071
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004072 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004073 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004074
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004075 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004076 VISIT(c, expr, e->v.FormattedValue.value);
4077
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004078 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004079 case 's': oparg = FVC_STR; break;
4080 case 'r': oparg = FVC_REPR; break;
4081 case 'a': oparg = FVC_ASCII; break;
4082 case -1: oparg = FVC_NONE; break;
4083 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004084 PyErr_Format(PyExc_SystemError,
4085 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004086 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004087 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004088 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004089 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004090 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004091 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004092 }
4093
Eric V. Smitha78c7952015-11-03 12:45:05 -05004094 /* And push our opcode and oparg */
4095 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004096
Eric V. Smith235a6f02015-09-19 14:51:32 -04004097 return 1;
4098}
4099
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004100static int
4101compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4102{
4103 Py_ssize_t i, n = end - begin;
4104 keyword_ty kw;
4105 PyObject *keys, *key;
4106 assert(n > 0);
4107 if (n > 1) {
4108 for (i = begin; i < end; i++) {
4109 kw = asdl_seq_GET(keywords, i);
4110 VISIT(c, expr, kw->value);
4111 }
4112 keys = PyTuple_New(n);
4113 if (keys == NULL) {
4114 return 0;
4115 }
4116 for (i = begin; i < end; i++) {
4117 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4118 Py_INCREF(key);
4119 PyTuple_SET_ITEM(keys, i - begin, key);
4120 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004121 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004122 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4123 }
4124 else {
4125 /* a for loop only executes once */
4126 for (i = begin; i < end; i++) {
4127 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004128 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004129 VISIT(c, expr, kw->value);
4130 }
4131 ADDOP_I(c, BUILD_MAP, n);
4132 }
4133 return 1;
4134}
4135
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004136/* shared code between compiler_call and compiler_class */
4137static int
4138compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004139 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004140 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004141 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004142{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004143 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004144 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004145
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004146 /* the number of tuples and dictionaries on the stack */
4147 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4148
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004149 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004150 nkwelts = asdl_seq_LEN(keywords);
4151
4152 for (i = 0; i < nkwelts; i++) {
4153 keyword_ty kw = asdl_seq_GET(keywords, i);
4154 if (kw->arg == NULL) {
4155 mustdictunpack = 1;
4156 break;
4157 }
4158 }
4159
4160 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004161 for (i = 0; i < nelts; i++) {
4162 expr_ty elt = asdl_seq_GET(args, i);
4163 if (elt->kind == Starred_kind) {
4164 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004165 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004166 if (nseen) {
4167 ADDOP_I(c, BUILD_TUPLE, nseen);
4168 nseen = 0;
4169 nsubargs++;
4170 }
4171 VISIT(c, expr, elt->v.Starred.value);
4172 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004173 }
4174 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004175 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004176 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004179
4180 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004181 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004182 if (nseen) {
4183 /* Pack up any trailing positional arguments. */
4184 ADDOP_I(c, BUILD_TUPLE, nseen);
4185 nsubargs++;
4186 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004187 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004188 /* If we ended up with more than one stararg, we need
4189 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004190 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004191 }
4192 else if (nsubargs == 0) {
4193 ADDOP_I(c, BUILD_TUPLE, 0);
4194 }
4195 nseen = 0; /* the number of keyword arguments on the stack following */
4196 for (i = 0; i < nkwelts; i++) {
4197 keyword_ty kw = asdl_seq_GET(keywords, i);
4198 if (kw->arg == NULL) {
4199 /* A keyword argument unpacking. */
4200 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004201 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4202 return 0;
4203 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004204 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004205 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004206 VISIT(c, expr, kw->value);
4207 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004208 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004209 else {
4210 nseen++;
4211 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004212 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004213 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004214 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004215 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004216 return 0;
4217 nsubkwargs++;
4218 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004219 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004220 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004221 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004222 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004223 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4224 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004226 else if (nkwelts) {
4227 PyObject *names;
4228 VISIT_SEQ(c, keyword, keywords);
4229 names = PyTuple_New(nkwelts);
4230 if (names == NULL) {
4231 return 0;
4232 }
4233 for (i = 0; i < nkwelts; i++) {
4234 keyword_ty kw = asdl_seq_GET(keywords, i);
4235 Py_INCREF(kw->arg);
4236 PyTuple_SET_ITEM(names, i, kw->arg);
4237 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004238 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004239 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4240 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004242 else {
4243 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4244 return 1;
4245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246}
4247
Nick Coghlan650f0d02007-04-15 12:05:43 +00004248
4249/* List and set comprehensions and generator expressions work by creating a
4250 nested function to perform the actual iteration. This means that the
4251 iteration variables don't leak into the current scope.
4252 The defined function is called immediately following its definition, with the
4253 result of that call being the result of the expression.
4254 The LC/SC version returns the populated container, while the GE version is
4255 flagged in symtable.c as a generator, so it returns the generator object
4256 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004257
4258 Possible cleanups:
4259 - iterate over the generator sequence instead of using recursion
4260*/
4261
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004263static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264compiler_comprehension_generator(struct compiler *c,
4265 asdl_seq *generators, int gen_index,
4266 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004267{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004268 comprehension_ty gen;
4269 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4270 if (gen->is_async) {
4271 return compiler_async_comprehension_generator(
4272 c, generators, gen_index, elt, val, type);
4273 } else {
4274 return compiler_sync_comprehension_generator(
4275 c, generators, gen_index, elt, val, type);
4276 }
4277}
4278
4279static int
4280compiler_sync_comprehension_generator(struct compiler *c,
4281 asdl_seq *generators, int gen_index,
4282 expr_ty elt, expr_ty val, int type)
4283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 /* generate code for the iterator, then each of the ifs,
4285 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 comprehension_ty gen;
4288 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004289 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004291 start = compiler_new_block(c);
4292 skip = compiler_new_block(c);
4293 if_cleanup = compiler_new_block(c);
4294 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4297 anchor == NULL)
4298 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 if (gen_index == 0) {
4303 /* Receive outermost iter as an implicit argument */
4304 c->u->u_argcount = 1;
4305 ADDOP_I(c, LOAD_FAST, 0);
4306 }
4307 else {
4308 /* Sub-iter - calculate on the fly */
4309 VISIT(c, expr, gen->iter);
4310 ADDOP(c, GET_ITER);
4311 }
4312 compiler_use_next_block(c, start);
4313 ADDOP_JREL(c, FOR_ITER, anchor);
4314 NEXT_BLOCK(c);
4315 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 /* XXX this needs to be cleaned up...a lot! */
4318 n = asdl_seq_LEN(gen->ifs);
4319 for (i = 0; i < n; i++) {
4320 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004321 if (!compiler_jump_if(c, e, if_cleanup, 0))
4322 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 NEXT_BLOCK(c);
4324 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (++gen_index < asdl_seq_LEN(generators))
4327 if (!compiler_comprehension_generator(c,
4328 generators, gen_index,
4329 elt, val, type))
4330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 /* only append after the last for generator */
4333 if (gen_index >= asdl_seq_LEN(generators)) {
4334 /* comprehension specific code */
4335 switch (type) {
4336 case COMP_GENEXP:
4337 VISIT(c, expr, elt);
4338 ADDOP(c, YIELD_VALUE);
4339 ADDOP(c, POP_TOP);
4340 break;
4341 case COMP_LISTCOMP:
4342 VISIT(c, expr, elt);
4343 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4344 break;
4345 case COMP_SETCOMP:
4346 VISIT(c, expr, elt);
4347 ADDOP_I(c, SET_ADD, gen_index + 1);
4348 break;
4349 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004350 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004353 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 ADDOP_I(c, MAP_ADD, gen_index + 1);
4355 break;
4356 default:
4357 return 0;
4358 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 compiler_use_next_block(c, skip);
4361 }
4362 compiler_use_next_block(c, if_cleanup);
4363 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4364 compiler_use_next_block(c, anchor);
4365
4366 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004367}
4368
4369static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004370compiler_async_comprehension_generator(struct compiler *c,
4371 asdl_seq *generators, int gen_index,
4372 expr_ty elt, expr_ty val, int type)
4373{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004374 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004375 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004377 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004378 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004379 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004380
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004381 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004382 return 0;
4383 }
4384
4385 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4386
4387 if (gen_index == 0) {
4388 /* Receive outermost iter as an implicit argument */
4389 c->u->u_argcount = 1;
4390 ADDOP_I(c, LOAD_FAST, 0);
4391 }
4392 else {
4393 /* Sub-iter - calculate on the fly */
4394 VISIT(c, expr, gen->iter);
4395 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 }
4397
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004398 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004399
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004400 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004401 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004402 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004403 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004405 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004406
4407 n = asdl_seq_LEN(gen->ifs);
4408 for (i = 0; i < n; i++) {
4409 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004410 if (!compiler_jump_if(c, e, if_cleanup, 0))
4411 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004412 NEXT_BLOCK(c);
4413 }
4414
4415 if (++gen_index < asdl_seq_LEN(generators))
4416 if (!compiler_comprehension_generator(c,
4417 generators, gen_index,
4418 elt, val, type))
4419 return 0;
4420
4421 /* only append after the last for generator */
4422 if (gen_index >= asdl_seq_LEN(generators)) {
4423 /* comprehension specific code */
4424 switch (type) {
4425 case COMP_GENEXP:
4426 VISIT(c, expr, elt);
4427 ADDOP(c, YIELD_VALUE);
4428 ADDOP(c, POP_TOP);
4429 break;
4430 case COMP_LISTCOMP:
4431 VISIT(c, expr, elt);
4432 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4433 break;
4434 case COMP_SETCOMP:
4435 VISIT(c, expr, elt);
4436 ADDOP_I(c, SET_ADD, gen_index + 1);
4437 break;
4438 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004439 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004440 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004441 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004442 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004443 ADDOP_I(c, MAP_ADD, gen_index + 1);
4444 break;
4445 default:
4446 return 0;
4447 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004448 }
4449 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004450 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4451
4452 compiler_use_next_block(c, except);
4453 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004454
4455 return 1;
4456}
4457
4458static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004459compiler_comprehension(struct compiler *c, expr_ty e, int type,
4460 identifier name, asdl_seq *generators, expr_ty elt,
4461 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004464 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004465 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004466 int is_async_function = c->u->u_ste->ste_coroutine;
4467 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004468
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004469 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004470
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004471 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4472 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004473 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004475 }
4476
4477 is_async_generator = c->u->u_ste->ste_coroutine;
4478
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004479 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480 compiler_error(c, "asynchronous comprehension outside of "
4481 "an asynchronous function");
4482 goto error_in_scope;
4483 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (type != COMP_GENEXP) {
4486 int op;
4487 switch (type) {
4488 case COMP_LISTCOMP:
4489 op = BUILD_LIST;
4490 break;
4491 case COMP_SETCOMP:
4492 op = BUILD_SET;
4493 break;
4494 case COMP_DICTCOMP:
4495 op = BUILD_MAP;
4496 break;
4497 default:
4498 PyErr_Format(PyExc_SystemError,
4499 "unknown comprehension type %d", type);
4500 goto error_in_scope;
4501 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 ADDOP_I(c, op, 0);
4504 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 if (!compiler_comprehension_generator(c, generators, 0, elt,
4507 val, type))
4508 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (type != COMP_GENEXP) {
4511 ADDOP(c, RETURN_VALUE);
4512 }
4513
4514 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004515 qualname = c->u->u_qualname;
4516 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004518 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 goto error;
4520
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004521 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004523 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 Py_DECREF(co);
4525
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 VISIT(c, expr, outermost->iter);
4527
4528 if (outermost->is_async) {
4529 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 } else {
4531 ADDOP(c, GET_ITER);
4532 }
4533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535
4536 if (is_async_generator && type != COMP_GENEXP) {
4537 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004538 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004539 ADDOP(c, YIELD_FROM);
4540 }
4541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004543error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004545error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004546 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 Py_XDECREF(co);
4548 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004549}
4550
4551static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004552compiler_genexp(struct compiler *c, expr_ty e)
4553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 static identifier name;
4555 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004556 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 if (!name)
4558 return 0;
4559 }
4560 assert(e->kind == GeneratorExp_kind);
4561 return compiler_comprehension(c, e, COMP_GENEXP, name,
4562 e->v.GeneratorExp.generators,
4563 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004564}
4565
4566static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004567compiler_listcomp(struct compiler *c, expr_ty e)
4568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 static identifier name;
4570 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004571 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 if (!name)
4573 return 0;
4574 }
4575 assert(e->kind == ListComp_kind);
4576 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4577 e->v.ListComp.generators,
4578 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004579}
4580
4581static int
4582compiler_setcomp(struct compiler *c, expr_ty e)
4583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 static identifier name;
4585 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004586 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 if (!name)
4588 return 0;
4589 }
4590 assert(e->kind == SetComp_kind);
4591 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4592 e->v.SetComp.generators,
4593 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004594}
4595
4596
4597static int
4598compiler_dictcomp(struct compiler *c, expr_ty e)
4599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 static identifier name;
4601 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004602 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 if (!name)
4604 return 0;
4605 }
4606 assert(e->kind == DictComp_kind);
4607 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4608 e->v.DictComp.generators,
4609 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004610}
4611
4612
4613static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004614compiler_visit_keyword(struct compiler *c, keyword_ty k)
4615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 VISIT(c, expr, k->value);
4617 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004618}
4619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004621 whether they are true or false.
4622
4623 Return values: 1 for true, 0 for false, -1 for non-constant.
4624 */
4625
4626static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004627expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004628{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004629 if (e->kind == Constant_kind) {
4630 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004631 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004632 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004633}
4634
Mark Shannonfee55262019-11-21 09:11:43 +00004635static int
4636compiler_with_except_finish(struct compiler *c) {
4637 basicblock *exit;
4638 exit = compiler_new_block(c);
4639 if (exit == NULL)
4640 return 0;
4641 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4642 ADDOP(c, RERAISE);
4643 compiler_use_next_block(c, exit);
4644 ADDOP(c, POP_TOP);
4645 ADDOP(c, POP_TOP);
4646 ADDOP(c, POP_TOP);
4647 ADDOP(c, POP_EXCEPT);
4648 ADDOP(c, POP_TOP);
4649 return 1;
4650}
Yury Selivanov75445082015-05-11 22:57:16 -04004651
4652/*
4653 Implements the async with statement.
4654
4655 The semantics outlined in that PEP are as follows:
4656
4657 async with EXPR as VAR:
4658 BLOCK
4659
4660 It is implemented roughly as:
4661
4662 context = EXPR
4663 exit = context.__aexit__ # not calling it
4664 value = await context.__aenter__()
4665 try:
4666 VAR = value # if VAR present in the syntax
4667 BLOCK
4668 finally:
4669 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004670 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004671 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004672 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004673 if not (await exit(*exc)):
4674 raise
4675 */
4676static int
4677compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4678{
Mark Shannonfee55262019-11-21 09:11:43 +00004679 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004680 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4681
4682 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004683 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4684 c->u->u_ste->ste_coroutine = 1;
4685 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004686 return compiler_error(c, "'async with' outside async function");
4687 }
Yury Selivanov75445082015-05-11 22:57:16 -04004688
4689 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004690 final = compiler_new_block(c);
4691 exit = compiler_new_block(c);
4692 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004693 return 0;
4694
4695 /* Evaluate EXPR */
4696 VISIT(c, expr, item->context_expr);
4697
4698 ADDOP(c, BEFORE_ASYNC_WITH);
4699 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004700 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004701 ADDOP(c, YIELD_FROM);
4702
Mark Shannonfee55262019-11-21 09:11:43 +00004703 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004704
4705 /* SETUP_ASYNC_WITH pushes a finally block. */
4706 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004707 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004708 return 0;
4709 }
4710
4711 if (item->optional_vars) {
4712 VISIT(c, expr, item->optional_vars);
4713 }
4714 else {
4715 /* Discard result from context.__aenter__() */
4716 ADDOP(c, POP_TOP);
4717 }
4718
4719 pos++;
4720 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4721 /* BLOCK code */
4722 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4723 else if (!compiler_async_with(c, s, pos))
4724 return 0;
4725
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004726 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004727 ADDOP(c, POP_BLOCK);
4728 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004729
Mark Shannonfee55262019-11-21 09:11:43 +00004730 /* For successful outcome:
4731 * call __exit__(None, None, None)
4732 */
4733 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004734 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004735 ADDOP(c, GET_AWAITABLE);
4736 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4737 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004738
Mark Shannonfee55262019-11-21 09:11:43 +00004739 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004740
Mark Shannonfee55262019-11-21 09:11:43 +00004741 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4742
4743 /* For exceptional outcome: */
4744 compiler_use_next_block(c, final);
4745
4746 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004747 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004748 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004749 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004750 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004751
Mark Shannonfee55262019-11-21 09:11:43 +00004752compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004753 return 1;
4754}
4755
4756
Guido van Rossumc2e20742006-02-27 22:32:47 +00004757/*
4758 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004759 with EXPR as VAR:
4760 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004761 is implemented as:
4762 <code for EXPR>
4763 SETUP_WITH E
4764 <code to store to VAR> or POP_TOP
4765 <code for BLOCK>
4766 LOAD_CONST (None, None, None)
4767 CALL_FUNCTION_EX 0
4768 JUMP_FORWARD EXIT
4769 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4770 POP_JUMP_IF_TRUE T:
4771 RERAISE
4772 T: POP_TOP * 3 (remove exception from stack)
4773 POP_EXCEPT
4774 POP_TOP
4775 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004776 */
Mark Shannonfee55262019-11-21 09:11:43 +00004777
Guido van Rossumc2e20742006-02-27 22:32:47 +00004778static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004779compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004780{
Mark Shannonfee55262019-11-21 09:11:43 +00004781 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004782 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004783
4784 assert(s->kind == With_kind);
4785
Guido van Rossumc2e20742006-02-27 22:32:47 +00004786 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004787 final = compiler_new_block(c);
4788 exit = compiler_new_block(c);
4789 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004790 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004791
Thomas Wouters477c8d52006-05-27 19:21:47 +00004792 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004793 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004794 /* Will push bound __exit__ */
4795 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004796
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004797 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004798 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004799 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004800 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004801 }
4802
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004803 if (item->optional_vars) {
4804 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004805 }
4806 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004808 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004809 }
4810
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004811 pos++;
4812 if (pos == asdl_seq_LEN(s->v.With.items))
4813 /* BLOCK code */
4814 VISIT_SEQ(c, stmt, s->v.With.body)
4815 else if (!compiler_with(c, s, pos))
4816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004817
Guido van Rossumc2e20742006-02-27 22:32:47 +00004818 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004819 compiler_pop_fblock(c, WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004820
4821 /* End of body; start the cleanup. */
4822
4823 /* For successful outcome:
4824 * call __exit__(None, None, None)
4825 */
4826 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004827 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004828 ADDOP(c, POP_TOP);
4829 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004830
Mark Shannonfee55262019-11-21 09:11:43 +00004831 /* For exceptional outcome: */
4832 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004833
Mark Shannonfee55262019-11-21 09:11:43 +00004834 ADDOP(c, WITH_EXCEPT_START);
4835 compiler_with_except_finish(c);
4836
4837 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004838 return 1;
4839}
4840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004841static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004842compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004845 case NamedExpr_kind:
4846 VISIT(c, expr, e->v.NamedExpr.value);
4847 ADDOP(c, DUP_TOP);
4848 VISIT(c, expr, e->v.NamedExpr.target);
4849 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 case BoolOp_kind:
4851 return compiler_boolop(c, e);
4852 case BinOp_kind:
4853 VISIT(c, expr, e->v.BinOp.left);
4854 VISIT(c, expr, e->v.BinOp.right);
4855 ADDOP(c, binop(c, e->v.BinOp.op));
4856 break;
4857 case UnaryOp_kind:
4858 VISIT(c, expr, e->v.UnaryOp.operand);
4859 ADDOP(c, unaryop(e->v.UnaryOp.op));
4860 break;
4861 case Lambda_kind:
4862 return compiler_lambda(c, e);
4863 case IfExp_kind:
4864 return compiler_ifexp(c, e);
4865 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004866 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004868 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 case GeneratorExp_kind:
4870 return compiler_genexp(c, e);
4871 case ListComp_kind:
4872 return compiler_listcomp(c, e);
4873 case SetComp_kind:
4874 return compiler_setcomp(c, e);
4875 case DictComp_kind:
4876 return compiler_dictcomp(c, e);
4877 case Yield_kind:
4878 if (c->u->u_ste->ste_type != FunctionBlock)
4879 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004880 if (e->v.Yield.value) {
4881 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 }
4883 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004884 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004886 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004888 case YieldFrom_kind:
4889 if (c->u->u_ste->ste_type != FunctionBlock)
4890 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004891
4892 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4893 return compiler_error(c, "'yield from' inside async function");
4894
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004895 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004896 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004897 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004898 ADDOP(c, YIELD_FROM);
4899 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004900 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004901 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4902 if (c->u->u_ste->ste_type != FunctionBlock){
4903 return compiler_error(c, "'await' outside function");
4904 }
Yury Selivanov75445082015-05-11 22:57:16 -04004905
Victor Stinner331a6a52019-05-27 16:39:22 +02004906 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004907 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4908 return compiler_error(c, "'await' outside async function");
4909 }
4910 }
Yury Selivanov75445082015-05-11 22:57:16 -04004911
4912 VISIT(c, expr, e->v.Await.value);
4913 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004914 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004915 ADDOP(c, YIELD_FROM);
4916 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 case Compare_kind:
4918 return compiler_compare(c, e);
4919 case Call_kind:
4920 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004921 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004922 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004923 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004924 case JoinedStr_kind:
4925 return compiler_joined_str(c, e);
4926 case FormattedValue_kind:
4927 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 /* The following exprs can be assignment targets. */
4929 case Attribute_kind:
4930 if (e->v.Attribute.ctx != AugStore)
4931 VISIT(c, expr, e->v.Attribute.value);
4932 switch (e->v.Attribute.ctx) {
4933 case AugLoad:
4934 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004935 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 case Load:
4937 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4938 break;
4939 case AugStore:
4940 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004941 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 case Store:
4943 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4944 break;
4945 case Del:
4946 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4947 break;
4948 case Param:
4949 default:
4950 PyErr_SetString(PyExc_SystemError,
4951 "param invalid in attribute expression");
4952 return 0;
4953 }
4954 break;
4955 case Subscript_kind:
4956 switch (e->v.Subscript.ctx) {
4957 case AugLoad:
4958 VISIT(c, expr, e->v.Subscript.value);
4959 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4960 break;
4961 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004962 if (!check_subscripter(c, e->v.Subscript.value)) {
4963 return 0;
4964 }
4965 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4966 return 0;
4967 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 VISIT(c, expr, e->v.Subscript.value);
4969 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4970 break;
4971 case AugStore:
4972 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4973 break;
4974 case Store:
4975 VISIT(c, expr, e->v.Subscript.value);
4976 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4977 break;
4978 case Del:
4979 VISIT(c, expr, e->v.Subscript.value);
4980 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4981 break;
4982 case Param:
4983 default:
4984 PyErr_SetString(PyExc_SystemError,
4985 "param invalid in subscript expression");
4986 return 0;
4987 }
4988 break;
4989 case Starred_kind:
4990 switch (e->v.Starred.ctx) {
4991 case Store:
4992 /* In all legitimate cases, the Starred node was already replaced
4993 * by compiler_list/compiler_tuple. XXX: is that okay? */
4994 return compiler_error(c,
4995 "starred assignment target must be in a list or tuple");
4996 default:
4997 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004998 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 case Name_kind:
5001 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5002 /* child nodes of List and Tuple will have expr_context set */
5003 case List_kind:
5004 return compiler_list(c, e);
5005 case Tuple_kind:
5006 return compiler_tuple(c, e);
5007 }
5008 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005009}
5010
5011static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005012compiler_visit_expr(struct compiler *c, expr_ty e)
5013{
5014 /* If expr e has a different line number than the last expr/stmt,
5015 set a new line number for the next instruction.
5016 */
5017 int old_lineno = c->u->u_lineno;
5018 int old_col_offset = c->u->u_col_offset;
5019 if (e->lineno != c->u->u_lineno) {
5020 c->u->u_lineno = e->lineno;
5021 c->u->u_lineno_set = 0;
5022 }
5023 /* Updating the column offset is always harmless. */
5024 c->u->u_col_offset = e->col_offset;
5025
5026 int res = compiler_visit_expr1(c, e);
5027
5028 if (old_lineno != c->u->u_lineno) {
5029 c->u->u_lineno = old_lineno;
5030 c->u->u_lineno_set = 0;
5031 }
5032 c->u->u_col_offset = old_col_offset;
5033 return res;
5034}
5035
5036static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005037compiler_augassign(struct compiler *c, stmt_ty s)
5038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 expr_ty e = s->v.AugAssign.target;
5040 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 switch (e->kind) {
5045 case Attribute_kind:
5046 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005047 AugLoad, e->lineno, e->col_offset,
5048 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 if (auge == NULL)
5050 return 0;
5051 VISIT(c, expr, auge);
5052 VISIT(c, expr, s->v.AugAssign.value);
5053 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5054 auge->v.Attribute.ctx = AugStore;
5055 VISIT(c, expr, auge);
5056 break;
5057 case Subscript_kind:
5058 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005059 AugLoad, e->lineno, e->col_offset,
5060 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 if (auge == NULL)
5062 return 0;
5063 VISIT(c, expr, auge);
5064 VISIT(c, expr, s->v.AugAssign.value);
5065 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5066 auge->v.Subscript.ctx = AugStore;
5067 VISIT(c, expr, auge);
5068 break;
5069 case Name_kind:
5070 if (!compiler_nameop(c, e->v.Name.id, Load))
5071 return 0;
5072 VISIT(c, expr, s->v.AugAssign.value);
5073 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5074 return compiler_nameop(c, e->v.Name.id, Store);
5075 default:
5076 PyErr_Format(PyExc_SystemError,
5077 "invalid node type (%d) for augmented assignment",
5078 e->kind);
5079 return 0;
5080 }
5081 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005082}
5083
5084static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005085check_ann_expr(struct compiler *c, expr_ty e)
5086{
5087 VISIT(c, expr, e);
5088 ADDOP(c, POP_TOP);
5089 return 1;
5090}
5091
5092static int
5093check_annotation(struct compiler *c, stmt_ty s)
5094{
5095 /* Annotations are only evaluated in a module or class. */
5096 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5097 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5098 return check_ann_expr(c, s->v.AnnAssign.annotation);
5099 }
5100 return 1;
5101}
5102
5103static int
5104check_ann_slice(struct compiler *c, slice_ty sl)
5105{
5106 switch(sl->kind) {
5107 case Index_kind:
5108 return check_ann_expr(c, sl->v.Index.value);
5109 case Slice_kind:
5110 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5111 return 0;
5112 }
5113 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5114 return 0;
5115 }
5116 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5117 return 0;
5118 }
5119 break;
5120 default:
5121 PyErr_SetString(PyExc_SystemError,
5122 "unexpected slice kind");
5123 return 0;
5124 }
5125 return 1;
5126}
5127
5128static int
5129check_ann_subscr(struct compiler *c, slice_ty sl)
5130{
5131 /* We check that everything in a subscript is defined at runtime. */
5132 Py_ssize_t i, n;
5133
5134 switch (sl->kind) {
5135 case Index_kind:
5136 case Slice_kind:
5137 if (!check_ann_slice(c, sl)) {
5138 return 0;
5139 }
5140 break;
5141 case ExtSlice_kind:
5142 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5143 for (i = 0; i < n; i++) {
5144 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5145 switch (subsl->kind) {
5146 case Index_kind:
5147 case Slice_kind:
5148 if (!check_ann_slice(c, subsl)) {
5149 return 0;
5150 }
5151 break;
5152 case ExtSlice_kind:
5153 default:
5154 PyErr_SetString(PyExc_SystemError,
5155 "extended slice invalid in nested slice");
5156 return 0;
5157 }
5158 }
5159 break;
5160 default:
5161 PyErr_Format(PyExc_SystemError,
5162 "invalid subscript kind %d", sl->kind);
5163 return 0;
5164 }
5165 return 1;
5166}
5167
5168static int
5169compiler_annassign(struct compiler *c, stmt_ty s)
5170{
5171 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005172 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005173
5174 assert(s->kind == AnnAssign_kind);
5175
5176 /* We perform the actual assignment first. */
5177 if (s->v.AnnAssign.value) {
5178 VISIT(c, expr, s->v.AnnAssign.value);
5179 VISIT(c, expr, targ);
5180 }
5181 switch (targ->kind) {
5182 case Name_kind:
5183 /* If we have a simple name in a module or class, store annotation. */
5184 if (s->v.AnnAssign.simple &&
5185 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5186 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005187 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5188 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5189 }
5190 else {
5191 VISIT(c, expr, s->v.AnnAssign.annotation);
5192 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005193 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005194 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005195 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005196 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197 }
5198 break;
5199 case Attribute_kind:
5200 if (!s->v.AnnAssign.value &&
5201 !check_ann_expr(c, targ->v.Attribute.value)) {
5202 return 0;
5203 }
5204 break;
5205 case Subscript_kind:
5206 if (!s->v.AnnAssign.value &&
5207 (!check_ann_expr(c, targ->v.Subscript.value) ||
5208 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5209 return 0;
5210 }
5211 break;
5212 default:
5213 PyErr_Format(PyExc_SystemError,
5214 "invalid node type (%d) for annotated assignment",
5215 targ->kind);
5216 return 0;
5217 }
5218 /* Annotation is evaluated last. */
5219 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5220 return 0;
5221 }
5222 return 1;
5223}
5224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005225/* Raises a SyntaxError and returns 0.
5226 If something goes wrong, a different exception may be raised.
5227*/
5228
5229static int
5230compiler_error(struct compiler *c, const char *errstr)
5231{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005232 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005234
Victor Stinner14e461d2013-08-26 22:28:21 +02005235 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 if (!loc) {
5237 Py_INCREF(Py_None);
5238 loc = Py_None;
5239 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005240 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005241 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 if (!u)
5243 goto exit;
5244 v = Py_BuildValue("(zO)", errstr, u);
5245 if (!v)
5246 goto exit;
5247 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005248 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 Py_DECREF(loc);
5250 Py_XDECREF(u);
5251 Py_XDECREF(v);
5252 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005253}
5254
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005255/* Emits a SyntaxWarning and returns 1 on success.
5256 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5257 and returns 0.
5258*/
5259static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005260compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005261{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005262 va_list vargs;
5263#ifdef HAVE_STDARG_PROTOTYPES
5264 va_start(vargs, format);
5265#else
5266 va_start(vargs);
5267#endif
5268 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5269 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005270 if (msg == NULL) {
5271 return 0;
5272 }
5273 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5274 c->u->u_lineno, NULL, NULL) < 0)
5275 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005276 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005277 /* Replace the SyntaxWarning exception with a SyntaxError
5278 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005279 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005280 assert(PyUnicode_AsUTF8(msg) != NULL);
5281 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005282 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005283 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005284 return 0;
5285 }
5286 Py_DECREF(msg);
5287 return 1;
5288}
5289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291compiler_handle_subscr(struct compiler *c, const char *kind,
5292 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 /* XXX this code is duplicated */
5297 switch (ctx) {
5298 case AugLoad: /* fall through to Load */
5299 case Load: op = BINARY_SUBSCR; break;
5300 case AugStore:/* fall through to Store */
5301 case Store: op = STORE_SUBSCR; break;
5302 case Del: op = DELETE_SUBSCR; break;
5303 case Param:
5304 PyErr_Format(PyExc_SystemError,
5305 "invalid %s kind %d in subscript\n",
5306 kind, ctx);
5307 return 0;
5308 }
5309 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005310 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 }
5312 else if (ctx == AugStore) {
5313 ADDOP(c, ROT_THREE);
5314 }
5315 ADDOP(c, op);
5316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317}
5318
5319static int
5320compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 int n = 2;
5323 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 /* only handles the cases where BUILD_SLICE is emitted */
5326 if (s->v.Slice.lower) {
5327 VISIT(c, expr, s->v.Slice.lower);
5328 }
5329 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005330 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 if (s->v.Slice.upper) {
5334 VISIT(c, expr, s->v.Slice.upper);
5335 }
5336 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005337 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 }
5339
5340 if (s->v.Slice.step) {
5341 n++;
5342 VISIT(c, expr, s->v.Slice.step);
5343 }
5344 ADDOP_I(c, BUILD_SLICE, n);
5345 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346}
5347
5348static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5350 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 switch (s->kind) {
5353 case Slice_kind:
5354 return compiler_slice(c, s, ctx);
5355 case Index_kind:
5356 VISIT(c, expr, s->v.Index.value);
5357 break;
5358 case ExtSlice_kind:
5359 default:
5360 PyErr_SetString(PyExc_SystemError,
5361 "extended slice invalid in nested slice");
5362 return 0;
5363 }
5364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005365}
5366
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005367static int
5368compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5369{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005370 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 switch (s->kind) {
5372 case Index_kind:
5373 kindname = "index";
5374 if (ctx != AugStore) {
5375 VISIT(c, expr, s->v.Index.value);
5376 }
5377 break;
5378 case Slice_kind:
5379 kindname = "slice";
5380 if (ctx != AugStore) {
5381 if (!compiler_slice(c, s, ctx))
5382 return 0;
5383 }
5384 break;
5385 case ExtSlice_kind:
5386 kindname = "extended slice";
5387 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005388 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 for (i = 0; i < n; i++) {
5390 slice_ty sub = (slice_ty)asdl_seq_GET(
5391 s->v.ExtSlice.dims, i);
5392 if (!compiler_visit_nested_slice(c, sub, ctx))
5393 return 0;
5394 }
5395 ADDOP_I(c, BUILD_TUPLE, n);
5396 }
5397 break;
5398 default:
5399 PyErr_Format(PyExc_SystemError,
5400 "invalid subscript kind %d", s->kind);
5401 return 0;
5402 }
5403 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404}
5405
Thomas Wouters89f507f2006-12-13 04:49:30 +00005406/* End of the compiler section, beginning of the assembler section */
5407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005409 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005410
5411 XXX must handle implicit jumps from one block to next
5412*/
5413
Thomas Wouters89f507f2006-12-13 04:49:30 +00005414struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 PyObject *a_bytecode; /* string containing bytecode */
5416 int a_offset; /* offset into bytecode */
5417 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005418 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 PyObject *a_lnotab; /* string containing lnotab */
5420 int a_lnotab_off; /* offset into lnotab */
5421 int a_lineno; /* last lineno of emitted instruction */
5422 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005423};
5424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425static void
T. Wouters99b54d62019-09-12 07:05:33 -07005426dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427{
T. Wouters99b54d62019-09-12 07:05:33 -07005428 int i, j;
5429
5430 /* Get rid of recursion for normal control flow.
5431 Since the number of blocks is limited, unused space in a_postorder
5432 (from a_nblocks to end) can be used as a stack for still not ordered
5433 blocks. */
5434 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005435 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005436 assert(a->a_nblocks < j);
5437 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 }
T. Wouters99b54d62019-09-12 07:05:33 -07005439 while (j < end) {
5440 b = a->a_postorder[j++];
5441 for (i = 0; i < b->b_iused; i++) {
5442 struct instr *instr = &b->b_instr[i];
5443 if (instr->i_jrel || instr->i_jabs)
5444 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005445 }
T. Wouters99b54d62019-09-12 07:05:33 -07005446 assert(a->a_nblocks < j);
5447 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005449}
5450
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005451Py_LOCAL_INLINE(void)
5452stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005454 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005455 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005456 assert(b->b_startdepth < 0);
5457 b->b_startdepth = depth;
5458 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005459 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005460}
5461
5462/* Find the flow path that needs the largest stack. We assume that
5463 * cycles in the flow graph have no net effect on the stack depth.
5464 */
5465static int
5466stackdepth(struct compiler *c)
5467{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005468 basicblock *b, *entryblock = NULL;
5469 basicblock **stack, **sp;
5470 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 b->b_startdepth = INT_MIN;
5473 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005474 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 }
5476 if (!entryblock)
5477 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5479 if (!stack) {
5480 PyErr_NoMemory();
5481 return -1;
5482 }
5483
5484 sp = stack;
5485 stackdepth_push(&sp, entryblock, 0);
5486 while (sp != stack) {
5487 b = *--sp;
5488 int depth = b->b_startdepth;
5489 assert(depth >= 0);
5490 basicblock *next = b->b_next;
5491 for (int i = 0; i < b->b_iused; i++) {
5492 struct instr *instr = &b->b_instr[i];
5493 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5494 if (effect == PY_INVALID_STACK_EFFECT) {
5495 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5496 Py_FatalError("PyCompile_OpcodeStackEffect()");
5497 }
5498 int new_depth = depth + effect;
5499 if (new_depth > maxdepth) {
5500 maxdepth = new_depth;
5501 }
5502 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5503 if (instr->i_jrel || instr->i_jabs) {
5504 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5505 assert(effect != PY_INVALID_STACK_EFFECT);
5506 int target_depth = depth + effect;
5507 if (target_depth > maxdepth) {
5508 maxdepth = target_depth;
5509 }
5510 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005511 stackdepth_push(&sp, instr->i_target, target_depth);
5512 }
5513 depth = new_depth;
5514 if (instr->i_opcode == JUMP_ABSOLUTE ||
5515 instr->i_opcode == JUMP_FORWARD ||
5516 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005517 instr->i_opcode == RAISE_VARARGS ||
5518 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005519 {
5520 /* remaining code is dead */
5521 next = NULL;
5522 break;
5523 }
5524 }
5525 if (next != NULL) {
5526 stackdepth_push(&sp, next, depth);
5527 }
5528 }
5529 PyObject_Free(stack);
5530 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005531}
5532
5533static int
5534assemble_init(struct assembler *a, int nblocks, int firstlineno)
5535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 memset(a, 0, sizeof(struct assembler));
5537 a->a_lineno = firstlineno;
5538 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5539 if (!a->a_bytecode)
5540 return 0;
5541 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5542 if (!a->a_lnotab)
5543 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005544 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 PyErr_NoMemory();
5546 return 0;
5547 }
T. Wouters99b54d62019-09-12 07:05:33 -07005548 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005550 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 PyErr_NoMemory();
5552 return 0;
5553 }
5554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555}
5556
5557static void
5558assemble_free(struct assembler *a)
5559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 Py_XDECREF(a->a_bytecode);
5561 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005562 if (a->a_postorder)
5563 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005564}
5565
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566static int
5567blocksize(basicblock *b)
5568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 int i;
5570 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005573 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005575}
5576
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005577/* Appends a pair to the end of the line number table, a_lnotab, representing
5578 the instruction's bytecode offset and line number. See
5579 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005580
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005581static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005582assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005585 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005587
Serhiy Storchakaab874002016-09-11 13:48:15 +03005588 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 if(d_bytecode == 0 && d_lineno == 0)
5594 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 if (d_bytecode > 255) {
5597 int j, nbytes, ncodes = d_bytecode / 255;
5598 nbytes = a->a_lnotab_off + 2 * ncodes;
5599 len = PyBytes_GET_SIZE(a->a_lnotab);
5600 if (nbytes >= len) {
5601 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5602 len = nbytes;
5603 else if (len <= INT_MAX / 2)
5604 len *= 2;
5605 else {
5606 PyErr_NoMemory();
5607 return 0;
5608 }
5609 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5610 return 0;
5611 }
5612 lnotab = (unsigned char *)
5613 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5614 for (j = 0; j < ncodes; j++) {
5615 *lnotab++ = 255;
5616 *lnotab++ = 0;
5617 }
5618 d_bytecode -= ncodes * 255;
5619 a->a_lnotab_off += ncodes * 2;
5620 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005621 assert(0 <= d_bytecode && d_bytecode <= 255);
5622
5623 if (d_lineno < -128 || 127 < d_lineno) {
5624 int j, nbytes, ncodes, k;
5625 if (d_lineno < 0) {
5626 k = -128;
5627 /* use division on positive numbers */
5628 ncodes = (-d_lineno) / 128;
5629 }
5630 else {
5631 k = 127;
5632 ncodes = d_lineno / 127;
5633 }
5634 d_lineno -= ncodes * k;
5635 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 nbytes = a->a_lnotab_off + 2 * ncodes;
5637 len = PyBytes_GET_SIZE(a->a_lnotab);
5638 if (nbytes >= len) {
5639 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5640 len = nbytes;
5641 else if (len <= INT_MAX / 2)
5642 len *= 2;
5643 else {
5644 PyErr_NoMemory();
5645 return 0;
5646 }
5647 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5648 return 0;
5649 }
5650 lnotab = (unsigned char *)
5651 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5652 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005653 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 d_bytecode = 0;
5655 for (j = 1; j < ncodes; j++) {
5656 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005657 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 a->a_lnotab_off += ncodes * 2;
5660 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005661 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 len = PyBytes_GET_SIZE(a->a_lnotab);
5664 if (a->a_lnotab_off + 2 >= len) {
5665 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5666 return 0;
5667 }
5668 lnotab = (unsigned char *)
5669 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 a->a_lnotab_off += 2;
5672 if (d_bytecode) {
5673 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005674 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 }
5676 else { /* First line of a block; def stmt, etc. */
5677 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005678 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 }
5680 a->a_lineno = i->i_lineno;
5681 a->a_lineno_off = a->a_offset;
5682 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005683}
5684
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005685/* assemble_emit()
5686 Extend the bytecode with a new instruction.
5687 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005688*/
5689
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005690static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005691assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005692{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005693 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005695 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005696
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005697 arg = i->i_oparg;
5698 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 if (i->i_lineno && !assemble_lnotab(a, i))
5700 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005701 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 if (len > PY_SSIZE_T_MAX / 2)
5703 return 0;
5704 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5705 return 0;
5706 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005707 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005709 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005711}
5712
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005713static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005714assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005717 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 /* Compute the size of each block and fixup jump args.
5721 Replace block pointer with position in bytecode. */
5722 do {
5723 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005724 for (i = a->a_nblocks - 1; i >= 0; i--) {
5725 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 bsize = blocksize(b);
5727 b->b_offset = totsize;
5728 totsize += bsize;
5729 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005730 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5732 bsize = b->b_offset;
5733 for (i = 0; i < b->b_iused; i++) {
5734 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005735 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 /* Relative jumps are computed relative to
5737 the instruction pointer after fetching
5738 the jump instruction.
5739 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 bsize += isize;
5741 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005743 if (instr->i_jrel) {
5744 instr->i_oparg -= bsize;
5745 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005746 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005747 if (instrsize(instr->i_oparg) != isize) {
5748 extended_arg_recompile = 1;
5749 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 }
5752 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 /* XXX: This is an awful hack that could hurt performance, but
5755 on the bright side it should work until we come up
5756 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 The issue is that in the first loop blocksize() is called
5759 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005760 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 So we loop until we stop seeing new EXTENDED_ARGs.
5764 The only EXTENDED_ARGs that could be popping up are
5765 ones in jump instructions. So this should converge
5766 fairly quickly.
5767 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005768 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005769}
5770
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005771static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005772dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005775 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 tuple = PyTuple_New(size);
5778 if (tuple == NULL)
5779 return NULL;
5780 while (PyDict_Next(dict, &pos, &k, &v)) {
5781 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005782 Py_INCREF(k);
5783 assert((i - offset) < size);
5784 assert((i - offset) >= 0);
5785 PyTuple_SET_ITEM(tuple, i - offset, k);
5786 }
5787 return tuple;
5788}
5789
5790static PyObject *
5791consts_dict_keys_inorder(PyObject *dict)
5792{
5793 PyObject *consts, *k, *v;
5794 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5795
5796 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5797 if (consts == NULL)
5798 return NULL;
5799 while (PyDict_Next(dict, &pos, &k, &v)) {
5800 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005801 /* The keys of the dictionary can be tuples wrapping a contant.
5802 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5803 * the object we want is always second. */
5804 if (PyTuple_CheckExact(k)) {
5805 k = PyTuple_GET_ITEM(k, 1);
5806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005808 assert(i < size);
5809 assert(i >= 0);
5810 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005812 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005813}
5814
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005815static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005816compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005819 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005821 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 if (ste->ste_nested)
5823 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005824 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005826 if (!ste->ste_generator && ste->ste_coroutine)
5827 flags |= CO_COROUTINE;
5828 if (ste->ste_generator && ste->ste_coroutine)
5829 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 if (ste->ste_varargs)
5831 flags |= CO_VARARGS;
5832 if (ste->ste_varkeywords)
5833 flags |= CO_VARKEYWORDS;
5834 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 /* (Only) inherit compilerflags in PyCF_MASK */
5837 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005838
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005839 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5840 ste->ste_coroutine &&
5841 !ste->ste_generator) {
5842 flags |= CO_COROUTINE;
5843 }
5844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005846}
5847
INADA Naokic2e16072018-11-26 21:23:22 +09005848// Merge *tuple* with constant cache.
5849// Unlike merge_consts_recursive(), this function doesn't work recursively.
5850static int
5851merge_const_tuple(struct compiler *c, PyObject **tuple)
5852{
5853 assert(PyTuple_CheckExact(*tuple));
5854
5855 PyObject *key = _PyCode_ConstantKey(*tuple);
5856 if (key == NULL) {
5857 return 0;
5858 }
5859
5860 // t is borrowed reference
5861 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5862 Py_DECREF(key);
5863 if (t == NULL) {
5864 return 0;
5865 }
5866 if (t == key) { // tuple is new constant.
5867 return 1;
5868 }
5869
5870 PyObject *u = PyTuple_GET_ITEM(t, 1);
5871 Py_INCREF(u);
5872 Py_DECREF(*tuple);
5873 *tuple = u;
5874 return 1;
5875}
5876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005877static PyCodeObject *
5878makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 PyObject *tmp;
5881 PyCodeObject *co = NULL;
5882 PyObject *consts = NULL;
5883 PyObject *names = NULL;
5884 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 PyObject *name = NULL;
5886 PyObject *freevars = NULL;
5887 PyObject *cellvars = NULL;
5888 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005889 Py_ssize_t nlocals;
5890 int nlocals_int;
5891 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005892 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005893
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005894 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 names = dict_keys_inorder(c->u->u_names, 0);
5896 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5897 if (!consts || !names || !varnames)
5898 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5901 if (!cellvars)
5902 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005903 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 if (!freevars)
5905 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005906
INADA Naokic2e16072018-11-26 21:23:22 +09005907 if (!merge_const_tuple(c, &names) ||
5908 !merge_const_tuple(c, &varnames) ||
5909 !merge_const_tuple(c, &cellvars) ||
5910 !merge_const_tuple(c, &freevars))
5911 {
5912 goto error;
5913 }
5914
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005915 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005916 assert(nlocals < INT_MAX);
5917 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 flags = compute_code_flags(c);
5920 if (flags < 0)
5921 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5924 if (!bytecode)
5925 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5928 if (!tmp)
5929 goto error;
5930 Py_DECREF(consts);
5931 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005932 if (!merge_const_tuple(c, &consts)) {
5933 goto error;
5934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005936 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005937 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005938 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005939 maxdepth = stackdepth(c);
5940 if (maxdepth < 0) {
5941 goto error;
5942 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005943 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5944 posonlyargcount, kwonlyargcount, nlocals_int,
5945 maxdepth, flags, bytecode, consts, names,
5946 varnames, freevars, cellvars, c->c_filename,
5947 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005948 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 Py_XDECREF(consts);
5950 Py_XDECREF(names);
5951 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 Py_XDECREF(name);
5953 Py_XDECREF(freevars);
5954 Py_XDECREF(cellvars);
5955 Py_XDECREF(bytecode);
5956 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005957}
5958
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005959
5960/* For debugging purposes only */
5961#if 0
5962static void
5963dump_instr(const struct instr *i)
5964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 const char *jrel = i->i_jrel ? "jrel " : "";
5966 const char *jabs = i->i_jabs ? "jabs " : "";
5967 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005970 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5974 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005975}
5976
5977static void
5978dump_basicblock(const basicblock *b)
5979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 const char *seen = b->b_seen ? "seen " : "";
5981 const char *b_return = b->b_return ? "return " : "";
5982 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5983 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5984 if (b->b_instr) {
5985 int i;
5986 for (i = 0; i < b->b_iused; i++) {
5987 fprintf(stderr, " [%02d] ", i);
5988 dump_instr(b->b_instr + i);
5989 }
5990 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005991}
5992#endif
5993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005994static PyCodeObject *
5995assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 basicblock *b, *entryblock;
5998 struct assembler a;
5999 int i, j, nblocks;
6000 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 /* Make sure every block that falls off the end returns None.
6003 XXX NEXT_BLOCK() isn't quite right, because if the last
6004 block ends with a jump or return b_next shouldn't set.
6005 */
6006 if (!c->u->u_curblock->b_return) {
6007 NEXT_BLOCK(c);
6008 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006009 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 ADDOP(c, RETURN_VALUE);
6011 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 nblocks = 0;
6014 entryblock = NULL;
6015 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6016 nblocks++;
6017 entryblock = b;
6018 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006020 /* Set firstlineno if it wasn't explicitly set. */
6021 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006022 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6024 else
6025 c->u->u_firstlineno = 1;
6026 }
6027 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6028 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006029 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006031 /* Can't modify the bytecode after computing jump offsets. */
6032 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006033
T. Wouters99b54d62019-09-12 07:05:33 -07006034 /* Emit code in reverse postorder from dfs. */
6035 for (i = a.a_nblocks - 1; i >= 0; i--) {
6036 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 for (j = 0; j < b->b_iused; j++)
6038 if (!assemble_emit(&a, &b->b_instr[j]))
6039 goto error;
6040 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6043 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006044 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006048 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 assemble_free(&a);
6050 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006051}
Georg Brandl8334fd92010-12-04 10:26:46 +00006052
6053#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006054PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006055PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6056 PyArena *arena)
6057{
6058 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6059}