blob: 913ec992395a06a8f7712c086d2956af36370066 [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
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Miss Islington (bot)92135772020-01-15 09:07:09 -080027#include "Python-ast.h"
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
Miss Islington (bot)f7e32fc2020-03-14 21:46:26 -070044#define IS_TOP_LEVEL_AWAIT(c) ( \
45 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
46 && (c->u->u_ste->ste_type == ModuleBlock))
47
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000048struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 unsigned i_jabs : 1;
50 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
72 unsigned b_seen : 1;
73 /* b_return is true if a RETURN_VALUE opcode is inserted. */
74 unsigned b_return : 1;
75 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
78 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
Serhiy Storchakaed146b52019-08-24 13:41:53 +030088enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_TRY2, FINALLY_END,
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020089 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000090
91struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 enum fblocktype fb_type;
93 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020094 /* (optional) type-specific exit or cleanup block */
95 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000096};
97
Antoine Pitrou86a36b52011-11-25 18:56:07 +010098enum {
99 COMPILER_SCOPE_MODULE,
100 COMPILER_SCOPE_CLASS,
101 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400102 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400103 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100104 COMPILER_SCOPE_COMPREHENSION,
105};
106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107/* The following items change on entry and exit of code blocks.
108 They must be saved and restored when returning to a block.
109*/
110struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400114 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100115 int u_scope_type;
116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 /* The following fields are dicts that map objects to
118 the index of them in co_XXX. The index is used as
119 the argument for opcodes that refer to those collections.
120 */
121 PyObject *u_consts; /* all constants */
122 PyObject *u_names; /* all names */
123 PyObject *u_varnames; /* local variables */
124 PyObject *u_cellvars; /* cell variables */
125 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100130 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100131 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 /* Pointer to the most recently allocated block. By following b_list
133 members, you can reach all early allocated blocks. */
134 basicblock *u_blocks;
135 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_nfblocks;
138 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 int u_firstlineno; /* the first lineno of the block */
141 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000142 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 int u_lineno_set; /* boolean to indicate whether instr
144 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000151managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000152
153Note that we don't track recursion levels during compilation - the
154task of detecting and rejecting excessive levels of nesting is
155handled by the symbol analysis pass.
156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157*/
158
159struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200160 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct symtable *c_st;
162 PyFutureFeatures *c_future; /* pointer to module's __future__ */
163 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164
Georg Brandl8334fd92010-12-04 10:26:46 +0000165 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 int c_interactive; /* true if in interactive mode */
167 int c_nestlevel;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700168 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
169 if this value is different from zero.
170 This can be used to temporarily visit
171 nodes without emitting bytecode to
172 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
INADA Naokic2e16072018-11-26 21:23:22 +0900174 PyObject *c_const_cache; /* Python dict holding all constants,
175 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 struct compiler_unit *u; /* compiler state for current block */
177 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
178 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179};
180
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100181static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000182static void compiler_free(struct compiler *);
183static basicblock *compiler_new_block(struct compiler *);
184static int compiler_next_instr(struct compiler *, basicblock *);
185static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100186static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200189static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
191
192static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
193static int compiler_visit_stmt(struct compiler *, stmt_ty);
194static int compiler_visit_keyword(struct compiler *, keyword_ty);
195static int compiler_visit_expr(struct compiler *, expr_ty);
196static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700197static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200202static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500204static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400205static int compiler_async_with(struct compiler *, stmt_ty, int);
206static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100207static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400209 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500210static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400211static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000212
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700213static int compiler_sync_comprehension_generator(
214 struct compiler *c,
215 asdl_seq *generators, int gen_index,
216 expr_ty elt, expr_ty val, int type);
217
218static int compiler_async_comprehension_generator(
219 struct compiler *c,
220 asdl_seq *generators, int gen_index,
221 expr_ty elt, expr_ty val, int type);
222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000224static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400226#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* Name mangling: __private becomes _classname__private.
232 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 PyObject *result;
234 size_t nlen, plen, ipriv;
235 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200237 PyUnicode_READ_CHAR(ident, 0) != '_' ||
238 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_INCREF(ident);
240 return ident;
241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 nlen = PyUnicode_GET_LENGTH(ident);
243 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 The only time a name with a dot can occur is when
247 we are compiling an import statement that has a
248 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 TODO(jhylton): Decide whether we want to support
251 mangling of the module name, e.g. __M.X.
252 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200253 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
254 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
255 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle __whatever__ */
258 }
259 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200260 ipriv = 0;
261 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
262 ipriv++;
263 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 Py_INCREF(ident);
265 return ident; /* Don't mangle if class is just underscores */
266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000268
Antoine Pitrou55bff892013-04-06 21:21:04 +0200269 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
270 PyErr_SetString(PyExc_OverflowError,
271 "private identifier too large to be mangled");
272 return NULL;
273 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
276 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
277 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
278
279 result = PyUnicode_New(1 + nlen + plen, maxchar);
280 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
283 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200284 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
285 Py_DECREF(result);
286 return NULL;
287 }
288 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
289 Py_DECREF(result);
290 return NULL;
291 }
Victor Stinner8f825062012-04-27 13:55:39 +0200292 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200293 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000294}
295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296static int
297compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000300
INADA Naokic2e16072018-11-26 21:23:22 +0900301 c->c_const_cache = PyDict_New();
302 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900304 }
305
306 c->c_stack = PyList_New(0);
307 if (!c->c_stack) {
308 Py_CLEAR(c->c_const_cache);
309 return 0;
310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313}
314
315PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200316PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
317 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 struct compiler c;
320 PyCodeObject *co = NULL;
Miss Islington (bot)92e836c2019-06-12 17:36:03 -0700321 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200323 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (!__doc__) {
326 __doc__ = PyUnicode_InternFromString("__doc__");
327 if (!__doc__)
328 return NULL;
329 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000330 if (!__annotations__) {
331 __annotations__ = PyUnicode_InternFromString("__annotations__");
332 if (!__annotations__)
333 return NULL;
334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (!compiler_init(&c))
336 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 c.c_filename = filename;
339 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200340 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (c.c_future == NULL)
342 goto finally;
343 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 flags = &local_flags;
345 }
346 merged = c.c_future->ff_features | flags->cf_flags;
347 c.c_future->ff_features = merged;
348 flags->cf_flags = merged;
349 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200350 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 c.c_nestlevel = 0;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700352 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200354 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900355 goto finally;
356 }
357
Victor Stinner14e461d2013-08-26 22:28:21 +0200358 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (c.c_st == NULL) {
360 if (!PyErr_Occurred())
361 PyErr_SetString(PyExc_SystemError, "no symtable");
362 goto finally;
363 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000366
Thomas Wouters1175c432006-02-27 22:49:54 +0000367 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 compiler_free(&c);
369 assert(co || PyErr_Occurred());
370 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371}
372
373PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200374PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
375 int optimize, PyArena *arena)
376{
377 PyObject *filename;
378 PyCodeObject *co;
379 filename = PyUnicode_DecodeFSDefault(filename_str);
380 if (filename == NULL)
381 return NULL;
382 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
383 Py_DECREF(filename);
384 return co;
385
386}
387
388PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389PyNode_Compile(struct _node *n, const char *filename)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyCodeObject *co = NULL;
392 mod_ty mod;
393 PyArena *arena = PyArena_New();
394 if (!arena)
395 return NULL;
396 mod = PyAST_FromNode(n, NULL, filename, arena);
397 if (mod)
398 co = PyAST_Compile(mod, filename, NULL, arena);
399 PyArena_Free(arena);
400 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000401}
402
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000403static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (c->c_st)
407 PySymtable_Free(c->c_st);
408 if (c->c_future)
409 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200410 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900411 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000413}
414
Guido van Rossum79f25d91997-04-29 20:08:16 +0000415static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000416list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 Py_ssize_t i, n;
419 PyObject *v, *k;
420 PyObject *dict = PyDict_New();
421 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 n = PyList_Size(list);
424 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100425 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (!v) {
427 Py_DECREF(dict);
428 return NULL;
429 }
430 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300431 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_DECREF(v);
433 Py_DECREF(dict);
434 return NULL;
435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 Py_DECREF(v);
437 }
438 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439}
440
441/* Return new dict containing names from src that match scope(s).
442
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000445values are integers, starting at offset and increasing by one for
446each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447*/
448
449static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100450dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700452 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500454 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 assert(offset >= 0);
457 if (dest == NULL)
458 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000459
Meador Inge2ca63152012-07-18 14:20:11 -0500460 /* Sort the keys so that we have a deterministic order on the indexes
461 saved in the returned dictionary. These indexes are used as indexes
462 into the free and cell var storage. Therefore if they aren't
463 deterministic, then the generated bytecode is not deterministic.
464 */
465 sorted_keys = PyDict_Keys(src);
466 if (sorted_keys == NULL)
467 return NULL;
468 if (PyList_Sort(sorted_keys) != 0) {
469 Py_DECREF(sorted_keys);
470 return NULL;
471 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500472 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500473
474 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* XXX this should probably be a macro in symtable.h */
476 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500477 k = PyList_GET_ITEM(sorted_keys, key_i);
478 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 assert(PyLong_Check(v));
480 vi = PyLong_AS_LONG(v);
481 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300484 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500486 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 Py_DECREF(dest);
488 return NULL;
489 }
490 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300491 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500492 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_DECREF(item);
494 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return NULL;
496 }
497 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 }
499 }
Meador Inge2ca63152012-07-18 14:20:11 -0500500 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000502}
503
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504static void
505compiler_unit_check(struct compiler_unit *u)
506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 basicblock *block;
508 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700509 assert((uintptr_t)block != 0xcbcbcbcbU);
510 assert((uintptr_t)block != 0xfbfbfbfbU);
511 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (block->b_instr != NULL) {
513 assert(block->b_ialloc > 0);
514 assert(block->b_iused > 0);
515 assert(block->b_ialloc >= block->b_iused);
516 }
517 else {
518 assert (block->b_iused == 0);
519 assert (block->b_ialloc == 0);
520 }
521 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522}
523
524static void
525compiler_unit_free(struct compiler_unit *u)
526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 compiler_unit_check(u);
530 b = u->u_blocks;
531 while (b != NULL) {
532 if (b->b_instr)
533 PyObject_Free((void *)b->b_instr);
534 next = b->b_list;
535 PyObject_Free((void *)b);
536 b = next;
537 }
538 Py_CLEAR(u->u_ste);
539 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400540 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 Py_CLEAR(u->u_consts);
542 Py_CLEAR(u->u_names);
543 Py_CLEAR(u->u_varnames);
544 Py_CLEAR(u->u_freevars);
545 Py_CLEAR(u->u_cellvars);
546 Py_CLEAR(u->u_private);
547 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548}
549
550static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100551compiler_enter_scope(struct compiler *c, identifier name,
552 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100555 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
558 struct compiler_unit));
559 if (!u) {
560 PyErr_NoMemory();
561 return 0;
562 }
563 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100564 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100566 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 u->u_kwonlyargcount = 0;
568 u->u_ste = PySymtable_Lookup(c->c_st, key);
569 if (!u->u_ste) {
570 compiler_unit_free(u);
571 return 0;
572 }
573 Py_INCREF(name);
574 u->u_name = name;
575 u->u_varnames = list2dict(u->u_ste->ste_varnames);
576 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
577 if (!u->u_varnames || !u->u_cellvars) {
578 compiler_unit_free(u);
579 return 0;
580 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000582 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300584 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500585 int res;
586 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200587 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 name = _PyUnicode_FromId(&PyId___class__);
589 if (!name) {
590 compiler_unit_free(u);
591 return 0;
592 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300593 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500594 if (res < 0) {
595 compiler_unit_free(u);
596 return 0;
597 }
598 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200601 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (!u->u_freevars) {
603 compiler_unit_free(u);
604 return 0;
605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_blocks = NULL;
608 u->u_nfblocks = 0;
609 u->u_firstlineno = lineno;
610 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000611 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_lineno_set = 0;
613 u->u_consts = PyDict_New();
614 if (!u->u_consts) {
615 compiler_unit_free(u);
616 return 0;
617 }
618 u->u_names = PyDict_New();
619 if (!u->u_names) {
620 compiler_unit_free(u);
621 return 0;
622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 /* Push the old compiler_unit on the stack. */
627 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400628 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
630 Py_XDECREF(capsule);
631 compiler_unit_free(u);
632 return 0;
633 }
634 Py_DECREF(capsule);
635 u->u_private = c->u->u_private;
636 Py_XINCREF(u->u_private);
637 }
638 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100641
642 block = compiler_new_block(c);
643 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100645 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400647 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
648 if (!compiler_set_qualname(c))
649 return 0;
650 }
651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653}
654
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000655static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656compiler_exit_scope(struct compiler *c)
657{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100658 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 c->c_nestlevel--;
662 compiler_unit_free(c->u);
663 /* Restore c->u to the parent unit. */
664 n = PyList_GET_SIZE(c->c_stack) - 1;
665 if (n >= 0) {
666 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400667 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 assert(c->u);
669 /* we are deleting from a list so this really shouldn't fail */
670 if (PySequence_DelItem(c->c_stack, n) < 0)
671 Py_FatalError("compiler_exit_scope()");
672 compiler_unit_check(c->u);
673 }
674 else
675 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677}
678
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679static int
680compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100682 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400683 _Py_static_string(dot_locals, ".<locals>");
684 Py_ssize_t stack_size;
685 struct compiler_unit *u = c->u;
686 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100687
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100689 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400690 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 if (stack_size > 1) {
692 int scope, force_global = 0;
693 struct compiler_unit *parent;
694 PyObject *mangled, *capsule;
695
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400696 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400697 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400698 assert(parent);
699
Yury Selivanov75445082015-05-11 22:57:16 -0400700 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
701 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
702 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 assert(u->u_name);
704 mangled = _Py_Mangle(parent->u_private, u->u_name);
705 if (!mangled)
706 return 0;
707 scope = PyST_GetScope(parent->u_ste, mangled);
708 Py_DECREF(mangled);
709 assert(scope != GLOBAL_IMPLICIT);
710 if (scope == GLOBAL_EXPLICIT)
711 force_global = 1;
712 }
713
714 if (!force_global) {
715 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400716 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400717 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
718 dot_locals_str = _PyUnicode_FromId(&dot_locals);
719 if (dot_locals_str == NULL)
720 return 0;
721 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
722 if (base == NULL)
723 return 0;
724 }
725 else {
726 Py_INCREF(parent->u_qualname);
727 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400728 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100729 }
730 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400731
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400732 if (base != NULL) {
733 dot_str = _PyUnicode_FromId(&dot);
734 if (dot_str == NULL) {
735 Py_DECREF(base);
736 return 0;
737 }
738 name = PyUnicode_Concat(base, dot_str);
739 Py_DECREF(base);
740 if (name == NULL)
741 return 0;
742 PyUnicode_Append(&name, u->u_name);
743 if (name == NULL)
744 return 0;
745 }
746 else {
747 Py_INCREF(u->u_name);
748 name = u->u_name;
749 }
750 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100751
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400752 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100753}
754
Eric V. Smith235a6f02015-09-19 14:51:32 -0400755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756/* Allocate a new block and return a pointer to it.
757 Returns NULL on error.
758*/
759
760static basicblock *
761compiler_new_block(struct compiler *c)
762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 basicblock *b;
764 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 u = c->u;
767 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
768 if (b == NULL) {
769 PyErr_NoMemory();
770 return NULL;
771 }
772 memset((void *)b, 0, sizeof(basicblock));
773 /* Extend the singly linked list of blocks with new block. */
774 b->b_list = u->u_blocks;
775 u->u_blocks = b;
776 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777}
778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780compiler_next_block(struct compiler *c)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 basicblock *block = compiler_new_block(c);
783 if (block == NULL)
784 return NULL;
785 c->u->u_curblock->b_next = block;
786 c->u->u_curblock = block;
787 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788}
789
790static basicblock *
791compiler_use_next_block(struct compiler *c, basicblock *block)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(block != NULL);
794 c->u->u_curblock->b_next = block;
795 c->u->u_curblock = block;
796 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000797}
798
799/* Returns the offset of the next instruction in the current block's
800 b_instr array. Resizes the b_instr as necessary.
801 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000802*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803
804static int
805compiler_next_instr(struct compiler *c, basicblock *b)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 assert(b != NULL);
808 if (b->b_instr == NULL) {
809 b->b_instr = (struct instr *)PyObject_Malloc(
810 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
811 if (b->b_instr == NULL) {
812 PyErr_NoMemory();
813 return -1;
814 }
815 b->b_ialloc = DEFAULT_BLOCK_SIZE;
816 memset((char *)b->b_instr, 0,
817 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
818 }
819 else if (b->b_iused == b->b_ialloc) {
820 struct instr *tmp;
821 size_t oldsize, newsize;
822 oldsize = b->b_ialloc * sizeof(struct instr);
823 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000824
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700825 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyErr_NoMemory();
827 return -1;
828 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (newsize == 0) {
831 PyErr_NoMemory();
832 return -1;
833 }
834 b->b_ialloc <<= 1;
835 tmp = (struct instr *)PyObject_Realloc(
836 (void *)b->b_instr, newsize);
837 if (tmp == NULL) {
838 PyErr_NoMemory();
839 return -1;
840 }
841 b->b_instr = tmp;
842 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
843 }
844 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845}
846
Christian Heimes2202f872008-02-06 14:31:34 +0000847/* Set the i_lineno member of the instruction at offset off if the
848 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849 already been set. If it has been set, the call has no effect.
850
Christian Heimes2202f872008-02-06 14:31:34 +0000851 The line number is reset in the following cases:
852 - when entering a new scope
853 - on each statement
854 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200855 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000856 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000857*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859static void
860compiler_set_lineno(struct compiler *c, int off)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 basicblock *b;
863 if (c->u->u_lineno_set)
864 return;
865 c->u->u_lineno_set = 1;
866 b = c->u->u_curblock;
867 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000868}
869
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200870/* Return the stack effect of opcode with argument oparg.
871
872 Some opcodes have different stack effect when jump to the target and
873 when not jump. The 'jump' parameter specifies the case:
874
875 * 0 -- when not jump
876 * 1 -- when jump
877 * -1 -- maximal
878 */
879/* XXX Make the stack effect of WITH_CLEANUP_START and
880 WITH_CLEANUP_FINISH deterministic. */
881static int
882stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300885 case NOP:
886 case EXTENDED_ARG:
887 return 0;
888
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200889 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 case POP_TOP:
891 return -1;
892 case ROT_TWO:
893 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200894 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return 0;
896 case DUP_TOP:
897 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000898 case DUP_TOP_TWO:
899 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case UNARY_POSITIVE:
903 case UNARY_NEGATIVE:
904 case UNARY_NOT:
905 case UNARY_INVERT:
906 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 case SET_ADD:
909 case LIST_APPEND:
910 return -1;
911 case MAP_ADD:
912 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000913
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200914 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case BINARY_POWER:
916 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400917 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case BINARY_MODULO:
919 case BINARY_ADD:
920 case BINARY_SUBTRACT:
921 case BINARY_SUBSCR:
922 case BINARY_FLOOR_DIVIDE:
923 case BINARY_TRUE_DIVIDE:
924 return -1;
925 case INPLACE_FLOOR_DIVIDE:
926 case INPLACE_TRUE_DIVIDE:
927 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case INPLACE_ADD:
930 case INPLACE_SUBTRACT:
931 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400932 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case INPLACE_MODULO:
934 return -1;
935 case STORE_SUBSCR:
936 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case DELETE_SUBSCR:
938 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case BINARY_LSHIFT:
941 case BINARY_RSHIFT:
942 case BINARY_AND:
943 case BINARY_XOR:
944 case BINARY_OR:
945 return -1;
946 case INPLACE_POWER:
947 return -1;
948 case GET_ITER:
949 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 case PRINT_EXPR:
952 return -1;
953 case LOAD_BUILD_CLASS:
954 return 1;
955 case INPLACE_LSHIFT:
956 case INPLACE_RSHIFT:
957 case INPLACE_AND:
958 case INPLACE_XOR:
959 case INPLACE_OR:
960 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200963 /* 1 in the normal flow.
964 * Restore the stack position and push 6 values before jumping to
965 * the handler if an exception be raised. */
966 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400967 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200968 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400969 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200970 /* Pop a variable number of values pushed by WITH_CLEANUP_START
971 * + __exit__ or __aexit__. */
972 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case RETURN_VALUE:
974 return -1;
975 case IMPORT_STAR:
976 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700977 case SETUP_ANNOTATIONS:
978 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case YIELD_VALUE:
980 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500981 case YIELD_FROM:
982 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case POP_BLOCK:
984 return 0;
985 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200986 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200988 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* Pop 6 values when an exception was raised. */
990 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case STORE_NAME:
993 return -1;
994 case DELETE_NAME:
995 return 0;
996 case UNPACK_SEQUENCE:
997 return oparg-1;
998 case UNPACK_EX:
999 return (oparg&0xFF) + (oparg>>8);
1000 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001001 /* -1 at end of iterator, 1 if continue iterating. */
1002 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case STORE_ATTR:
1005 return -2;
1006 case DELETE_ATTR:
1007 return -1;
1008 case STORE_GLOBAL:
1009 return -1;
1010 case DELETE_GLOBAL:
1011 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 case LOAD_CONST:
1013 return 1;
1014 case LOAD_NAME:
1015 return 1;
1016 case BUILD_TUPLE:
1017 case BUILD_LIST:
1018 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001019 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001021 case BUILD_LIST_UNPACK:
1022 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001023 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001024 case BUILD_SET_UNPACK:
1025 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001026 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001027 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001029 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001030 case BUILD_CONST_KEY_MAP:
1031 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case LOAD_ATTR:
1033 return 0;
1034 case COMPARE_OP:
1035 return -1;
1036 case IMPORT_NAME:
1037 return -1;
1038 case IMPORT_FROM:
1039 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001041 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case JUMP_ABSOLUTE:
1044 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001046 case JUMP_IF_TRUE_OR_POP:
1047 case JUMP_IF_FALSE_OR_POP:
1048 return jump ? 0 : -1;
1049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case POP_JUMP_IF_FALSE:
1051 case POP_JUMP_IF_TRUE:
1052 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 case LOAD_GLOBAL:
1055 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001057 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059 /* 0 in the normal flow.
1060 * Restore the stack position and push 6 values before jumping to
1061 * the handler if an exception be raised. */
1062 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001063 case BEGIN_FINALLY:
1064 /* Actually pushes 1 value, but count 6 for balancing with
1065 * END_FINALLY and POP_FINALLY.
1066 * This is the main reason of using this opcode instead of
1067 * "LOAD_CONST None". */
1068 return 6;
1069 case CALL_FINALLY:
1070 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case LOAD_FAST:
1073 return 1;
1074 case STORE_FAST:
1075 return -1;
1076 case DELETE_FAST:
1077 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case RAISE_VARARGS:
1080 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001081
1082 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001084 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001085 case CALL_METHOD:
1086 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001088 return -oparg-1;
1089 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001090 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001091 case MAKE_FUNCTION:
1092 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1093 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 case BUILD_SLICE:
1095 if (oparg == 3)
1096 return -2;
1097 else
1098 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 case LOAD_CLOSURE:
1102 return 1;
1103 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001104 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 return 1;
1106 case STORE_DEREF:
1107 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001108 case DELETE_DEREF:
1109 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001110
1111 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001112 case GET_AWAITABLE:
1113 return 0;
1114 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001115 /* 0 in the normal flow.
1116 * Restore the stack position to the position before the result
1117 * of __aenter__ and push 6 values before jumping to the handler
1118 * if an exception be raised. */
1119 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001120 case BEFORE_ASYNC_WITH:
1121 return 1;
1122 case GET_AITER:
1123 return 0;
1124 case GET_ANEXT:
1125 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001126 case GET_YIELD_FROM_ITER:
1127 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001128 case END_ASYNC_FOR:
1129 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001130 case FORMAT_VALUE:
1131 /* If there's a fmt_spec on the stack, we go from 2->1,
1132 else 1->1. */
1133 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001134 case LOAD_METHOD:
1135 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001137 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
Larry Hastings3a907972013-11-23 14:49:22 -08001139 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140}
1141
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001142int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001143PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1144{
1145 return stack_effect(opcode, oparg, jump);
1146}
1147
1148int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001149PyCompile_OpcodeStackEffect(int opcode, int oparg)
1150{
1151 return stack_effect(opcode, oparg, -1);
1152}
1153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154/* Add an opcode with no argument.
1155 Returns 0 on failure, 1 on success.
1156*/
1157
1158static int
1159compiler_addop(struct compiler *c, int opcode)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 basicblock *b;
1162 struct instr *i;
1163 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001164 assert(!HAS_ARG(opcode));
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001165 if (c->c_do_not_emit_bytecode) {
1166 return 1;
1167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 off = compiler_next_instr(c, c->u->u_curblock);
1169 if (off < 0)
1170 return 0;
1171 b = c->u->u_curblock;
1172 i = &b->b_instr[off];
1173 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001174 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (opcode == RETURN_VALUE)
1176 b->b_return = 1;
1177 compiler_set_lineno(c, off);
1178 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179}
1180
Victor Stinnerf8e32212013-11-19 23:56:34 +01001181static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1183{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001184 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001187 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001189 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001191 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001192 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001193 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 return -1;
1196 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001197 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 Py_DECREF(v);
1199 return -1;
1200 }
1201 Py_DECREF(v);
1202 }
1203 else
1204 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001205 return arg;
1206}
1207
INADA Naokic2e16072018-11-26 21:23:22 +09001208// Merge const *o* recursively and return constant key object.
1209static PyObject*
1210merge_consts_recursive(struct compiler *c, PyObject *o)
1211{
1212 // None and Ellipsis are singleton, and key is the singleton.
1213 // No need to merge object and key.
1214 if (o == Py_None || o == Py_Ellipsis) {
1215 Py_INCREF(o);
1216 return o;
1217 }
1218
1219 PyObject *key = _PyCode_ConstantKey(o);
1220 if (key == NULL) {
1221 return NULL;
1222 }
1223
1224 // t is borrowed reference
1225 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1226 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001227 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001228 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001229 Py_DECREF(key);
1230 return t;
1231 }
1232
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001234 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001235 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001236 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001237 Py_ssize_t len = PyTuple_GET_SIZE(o);
1238 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001239 PyObject *item = PyTuple_GET_ITEM(o, i);
1240 PyObject *u = merge_consts_recursive(c, item);
1241 if (u == NULL) {
1242 Py_DECREF(key);
1243 return NULL;
1244 }
1245
1246 // See _PyCode_ConstantKey()
1247 PyObject *v; // borrowed
1248 if (PyTuple_CheckExact(u)) {
1249 v = PyTuple_GET_ITEM(u, 1);
1250 }
1251 else {
1252 v = u;
1253 }
1254 if (v != item) {
1255 Py_INCREF(v);
1256 PyTuple_SET_ITEM(o, i, v);
1257 Py_DECREF(item);
1258 }
1259
1260 Py_DECREF(u);
1261 }
1262 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001263 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001264 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001265 // constant keys.
1266 // See _PyCode_ConstantKey() for detail.
1267 assert(PyTuple_CheckExact(key));
1268 assert(PyTuple_GET_SIZE(key) == 2);
1269
1270 Py_ssize_t len = PySet_GET_SIZE(o);
1271 if (len == 0) { // empty frozenset should not be re-created.
1272 return key;
1273 }
1274 PyObject *tuple = PyTuple_New(len);
1275 if (tuple == NULL) {
1276 Py_DECREF(key);
1277 return NULL;
1278 }
1279 Py_ssize_t i = 0, pos = 0;
1280 PyObject *item;
1281 Py_hash_t hash;
1282 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1283 PyObject *k = merge_consts_recursive(c, item);
1284 if (k == NULL) {
1285 Py_DECREF(tuple);
1286 Py_DECREF(key);
1287 return NULL;
1288 }
1289 PyObject *u;
1290 if (PyTuple_CheckExact(k)) {
1291 u = PyTuple_GET_ITEM(k, 1);
1292 Py_INCREF(u);
1293 Py_DECREF(k);
1294 }
1295 else {
1296 u = k;
1297 }
1298 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1299 i++;
1300 }
1301
1302 // Instead of rewriting o, we create new frozenset and embed in the
1303 // key tuple. Caller should get merged frozenset from the key tuple.
1304 PyObject *new = PyFrozenSet_New(tuple);
1305 Py_DECREF(tuple);
1306 if (new == NULL) {
1307 Py_DECREF(key);
1308 return NULL;
1309 }
1310 assert(PyTuple_GET_ITEM(key, 1) == o);
1311 Py_DECREF(o);
1312 PyTuple_SET_ITEM(key, 1, new);
1313 }
INADA Naokic2e16072018-11-26 21:23:22 +09001314
1315 return key;
1316}
1317
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001318static Py_ssize_t
1319compiler_add_const(struct compiler *c, PyObject *o)
1320{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001321 if (c->c_do_not_emit_bytecode) {
1322 return 0;
1323 }
1324
INADA Naokic2e16072018-11-26 21:23:22 +09001325 PyObject *key = merge_consts_recursive(c, o);
1326 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001327 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001328 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001329
INADA Naokic2e16072018-11-26 21:23:22 +09001330 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1331 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333}
1334
1335static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001336compiler_addop_load_const(struct compiler *c, PyObject *o)
1337{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001338 if (c->c_do_not_emit_bytecode) {
1339 return 1;
1340 }
1341
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001342 Py_ssize_t arg = compiler_add_const(c, o);
1343 if (arg < 0)
1344 return 0;
1345 return compiler_addop_i(c, LOAD_CONST, arg);
1346}
1347
1348static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001352 if (c->c_do_not_emit_bytecode) {
1353 return 1;
1354 }
1355
Victor Stinnerad9a0662013-11-19 22:23:20 +01001356 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001358 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 return compiler_addop_i(c, opcode, arg);
1360}
1361
1362static int
1363compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001366 Py_ssize_t arg;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001367
1368 if (c->c_do_not_emit_bytecode) {
1369 return 1;
1370 }
1371
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001372 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1373 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 arg = compiler_add_o(c, dict, mangled);
1376 Py_DECREF(mangled);
1377 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 return compiler_addop_i(c, opcode, arg);
1380}
1381
1382/* Add an opcode with an integer argument.
1383 Returns 0 on failure, 1 on success.
1384*/
1385
1386static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001387compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 struct instr *i;
1390 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001391
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001392 if (c->c_do_not_emit_bytecode) {
1393 return 1;
1394 }
1395
Victor Stinner2ad474b2016-03-01 23:34:47 +01001396 /* oparg value is unsigned, but a signed C int is usually used to store
1397 it in the C code (like Python/ceval.c).
1398
1399 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1400
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001401 The argument of a concrete bytecode instruction is limited to 8-bit.
1402 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1403 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001404 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 off = compiler_next_instr(c, c->u->u_curblock);
1407 if (off < 0)
1408 return 0;
1409 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001410 i->i_opcode = opcode;
1411 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 compiler_set_lineno(c, off);
1413 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414}
1415
1416static int
1417compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 struct instr *i;
1420 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001422 if (c->c_do_not_emit_bytecode) {
1423 return 1;
1424 }
1425
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001426 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 assert(b != NULL);
1428 off = compiler_next_instr(c, c->u->u_curblock);
1429 if (off < 0)
1430 return 0;
1431 i = &c->u->u_curblock->b_instr[off];
1432 i->i_opcode = opcode;
1433 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (absolute)
1435 i->i_jabs = 1;
1436 else
1437 i->i_jrel = 1;
1438 compiler_set_lineno(c, off);
1439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001442/* NEXT_BLOCK() creates an implicit jump from the current block
1443 to the new block.
1444
1445 The returns inside this macro make it impossible to decref objects
1446 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (compiler_next_block((C)) == NULL) \
1450 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451}
1452
1453#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (!compiler_addop((C), (OP))) \
1455 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456}
1457
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001458#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (!compiler_addop((C), (OP))) { \
1460 compiler_exit_scope(c); \
1461 return 0; \
1462 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001463}
1464
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001465#define ADDOP_LOAD_CONST(C, O) { \
1466 if (!compiler_addop_load_const((C), (O))) \
1467 return 0; \
1468}
1469
1470/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1471#define ADDOP_LOAD_CONST_NEW(C, O) { \
1472 PyObject *__new_const = (O); \
1473 if (__new_const == NULL) { \
1474 return 0; \
1475 } \
1476 if (!compiler_addop_load_const((C), __new_const)) { \
1477 Py_DECREF(__new_const); \
1478 return 0; \
1479 } \
1480 Py_DECREF(__new_const); \
1481}
1482
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1485 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486}
1487
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001488/* Same as ADDOP_O, but steals a reference. */
1489#define ADDOP_N(C, OP, O, TYPE) { \
1490 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1491 Py_DECREF((O)); \
1492 return 0; \
1493 } \
1494 Py_DECREF((O)); \
1495}
1496
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1499 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
1502#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (!compiler_addop_i((C), (OP), (O))) \
1504 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
1507#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (!compiler_addop_j((C), (OP), (O), 1)) \
1509 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510}
1511
1512#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!compiler_addop_j((C), (OP), (O), 0)) \
1514 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515}
1516
1517/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1518 the ASDL name to synthesize the name of the C type and the visit function.
1519*/
1520
1521#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_visit_ ## TYPE((C), (V))) \
1523 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001526#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (!compiler_visit_ ## TYPE((C), (V))) { \
1528 compiler_exit_scope(c); \
1529 return 0; \
1530 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001531}
1532
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (!compiler_visit_slice((C), (V), (CTX))) \
1535 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536}
1537
1538#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 int _i; \
1540 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1541 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1542 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1543 if (!compiler_visit_ ## TYPE((C), elt)) \
1544 return 0; \
1545 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546}
1547
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001548#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 int _i; \
1550 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1551 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1552 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1553 if (!compiler_visit_ ## TYPE((C), elt)) { \
1554 compiler_exit_scope(c); \
1555 return 0; \
1556 } \
1557 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001558}
1559
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001560/* These macros allows to check only for errors and not emmit bytecode
1561 * while visiting nodes.
1562*/
1563
1564#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1565 c->c_do_not_emit_bytecode++;
1566
1567#define END_DO_NOT_EMIT_BYTECODE \
1568 c->c_do_not_emit_bytecode--; \
1569}
1570
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001571/* Search if variable annotations are present statically in a block. */
1572
1573static int
1574find_ann(asdl_seq *stmts)
1575{
1576 int i, j, res = 0;
1577 stmt_ty st;
1578
1579 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1580 st = (stmt_ty)asdl_seq_GET(stmts, i);
1581 switch (st->kind) {
1582 case AnnAssign_kind:
1583 return 1;
1584 case For_kind:
1585 res = find_ann(st->v.For.body) ||
1586 find_ann(st->v.For.orelse);
1587 break;
1588 case AsyncFor_kind:
1589 res = find_ann(st->v.AsyncFor.body) ||
1590 find_ann(st->v.AsyncFor.orelse);
1591 break;
1592 case While_kind:
1593 res = find_ann(st->v.While.body) ||
1594 find_ann(st->v.While.orelse);
1595 break;
1596 case If_kind:
1597 res = find_ann(st->v.If.body) ||
1598 find_ann(st->v.If.orelse);
1599 break;
1600 case With_kind:
1601 res = find_ann(st->v.With.body);
1602 break;
1603 case AsyncWith_kind:
1604 res = find_ann(st->v.AsyncWith.body);
1605 break;
1606 case Try_kind:
1607 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1608 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1609 st->v.Try.handlers, j);
1610 if (find_ann(handler->v.ExceptHandler.body)) {
1611 return 1;
1612 }
1613 }
1614 res = find_ann(st->v.Try.body) ||
1615 find_ann(st->v.Try.finalbody) ||
1616 find_ann(st->v.Try.orelse);
1617 break;
1618 default:
1619 res = 0;
1620 }
1621 if (res) {
1622 break;
1623 }
1624 }
1625 return res;
1626}
1627
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001628/*
1629 * Frame block handling functions
1630 */
1631
1632static int
1633compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1634 basicblock *exit)
1635{
1636 struct fblockinfo *f;
1637 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1638 PyErr_SetString(PyExc_SyntaxError,
1639 "too many statically nested blocks");
1640 return 0;
1641 }
1642 f = &c->u->u_fblock[c->u->u_nfblocks++];
1643 f->fb_type = t;
1644 f->fb_block = b;
1645 f->fb_exit = exit;
1646 return 1;
1647}
1648
1649static void
1650compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1651{
1652 struct compiler_unit *u = c->u;
1653 assert(u->u_nfblocks > 0);
1654 u->u_nfblocks--;
1655 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1656 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1657}
1658
1659/* Unwind a frame block. If preserve_tos is true, the TOS before
1660 * popping the blocks will be restored afterwards.
1661 */
1662static int
1663compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1664 int preserve_tos)
1665{
1666 switch (info->fb_type) {
1667 case WHILE_LOOP:
1668 return 1;
1669
1670 case FINALLY_END:
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001671 info->fb_exit = NULL;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001672 ADDOP_I(c, POP_FINALLY, preserve_tos);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001673 if (preserve_tos) {
1674 ADDOP(c, ROT_TWO);
1675 }
1676 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001677 return 1;
1678
1679 case FOR_LOOP:
1680 /* Pop the iterator */
1681 if (preserve_tos) {
1682 ADDOP(c, ROT_TWO);
1683 }
1684 ADDOP(c, POP_TOP);
1685 return 1;
1686
1687 case EXCEPT:
1688 ADDOP(c, POP_BLOCK);
1689 return 1;
1690
1691 case FINALLY_TRY:
1692 ADDOP(c, POP_BLOCK);
1693 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1694 return 1;
1695
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001696 case FINALLY_TRY2:
1697 ADDOP(c, POP_BLOCK);
1698 if (preserve_tos) {
1699 ADDOP(c, ROT_TWO);
1700 ADDOP(c, POP_TOP);
1701 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1702 }
1703 else {
1704 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1705 ADDOP(c, POP_TOP);
1706 }
1707 return 1;
1708
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001709 case WITH:
1710 case ASYNC_WITH:
1711 ADDOP(c, POP_BLOCK);
1712 if (preserve_tos) {
1713 ADDOP(c, ROT_TWO);
1714 }
1715 ADDOP(c, BEGIN_FINALLY);
1716 ADDOP(c, WITH_CLEANUP_START);
1717 if (info->fb_type == ASYNC_WITH) {
1718 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001719 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001720 ADDOP(c, YIELD_FROM);
1721 }
1722 ADDOP(c, WITH_CLEANUP_FINISH);
1723 ADDOP_I(c, POP_FINALLY, 0);
1724 return 1;
1725
1726 case HANDLER_CLEANUP:
1727 if (preserve_tos) {
1728 ADDOP(c, ROT_FOUR);
1729 }
1730 if (info->fb_exit) {
1731 ADDOP(c, POP_BLOCK);
1732 ADDOP(c, POP_EXCEPT);
1733 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1734 }
1735 else {
1736 ADDOP(c, POP_EXCEPT);
1737 }
1738 return 1;
1739 }
1740 Py_UNREACHABLE();
1741}
1742
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001743/* Compile a sequence of statements, checking for a docstring
1744 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745
1746static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001747compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001748{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001749 int i = 0;
1750 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001751 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001752
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001753 /* Set current line number to the line number of first statement.
1754 This way line number for SETUP_ANNOTATIONS will always
1755 coincide with the line number of first "real" statement in module.
Miss Islington (bot)d8071cb2019-10-08 19:42:22 -07001756 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001757 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1758 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001759 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001760 c->u->u_lineno = st->lineno;
1761 }
1762 /* Every annotated class and module should have __annotations__. */
1763 if (find_ann(stmts)) {
1764 ADDOP(c, SETUP_ANNOTATIONS);
1765 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001766 if (!asdl_seq_LEN(stmts))
1767 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001768 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001769 if (c->c_optimize < 2) {
1770 docstring = _PyAST_GetDocString(stmts);
1771 if (docstring) {
1772 i = 1;
1773 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1774 assert(st->kind == Expr_kind);
1775 VISIT(c, expr, st->v.Expr.value);
1776 if (!compiler_nameop(c, __doc__, Store))
1777 return 0;
1778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001780 for (; i < asdl_seq_LEN(stmts); i++)
1781 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783}
1784
1785static PyCodeObject *
1786compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCodeObject *co;
1789 int addNone = 1;
1790 static PyObject *module;
1791 if (!module) {
1792 module = PyUnicode_InternFromString("<module>");
1793 if (!module)
1794 return NULL;
1795 }
1796 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001797 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return NULL;
1799 switch (mod->kind) {
1800 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001801 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 compiler_exit_scope(c);
1803 return 0;
1804 }
1805 break;
1806 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001807 if (find_ann(mod->v.Interactive.body)) {
1808 ADDOP(c, SETUP_ANNOTATIONS);
1809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 c->c_interactive = 1;
1811 VISIT_SEQ_IN_SCOPE(c, stmt,
1812 mod->v.Interactive.body);
1813 break;
1814 case Expression_kind:
1815 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1816 addNone = 0;
1817 break;
1818 case Suite_kind:
1819 PyErr_SetString(PyExc_SystemError,
1820 "suite should not be possible");
1821 return 0;
1822 default:
1823 PyErr_Format(PyExc_SystemError,
1824 "module kind %d should not be possible",
1825 mod->kind);
1826 return 0;
1827 }
1828 co = assemble(c, addNone);
1829 compiler_exit_scope(c);
1830 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001831}
1832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833/* The test for LOCAL must come before the test for FREE in order to
1834 handle classes where name is both local and free. The local var is
1835 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001836*/
1837
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838static int
1839get_ref_type(struct compiler *c, PyObject *name)
1840{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001841 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001842 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001843 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001844 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001845 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (scope == 0) {
1847 char buf[350];
1848 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001849 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001851 PyUnicode_AsUTF8(name),
1852 PyUnicode_AsUTF8(c->u->u_name),
1853 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1854 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1855 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1856 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 );
1858 Py_FatalError(buf);
1859 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862}
1863
1864static int
1865compiler_lookup_arg(PyObject *dict, PyObject *name)
1866{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001867 PyObject *v;
1868 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001870 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001871 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872}
1873
1874static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001875compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001877 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001878 if (qualname == NULL)
1879 qualname = co->co_name;
1880
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001881 if (free) {
1882 for (i = 0; i < free; ++i) {
1883 /* Bypass com_addop_varname because it will generate
1884 LOAD_DEREF but LOAD_CLOSURE is needed.
1885 */
1886 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1887 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001889 /* Special case: If a class contains a method with a
1890 free variable that has the same name as a method,
1891 the name will be considered free *and* local in the
1892 class. It should be handled by the closure, as
1893 well as by the normal name loookup logic.
1894 */
1895 reftype = get_ref_type(c, name);
1896 if (reftype == CELL)
1897 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1898 else /* (reftype == FREE) */
1899 arg = compiler_lookup_arg(c->u->u_freevars, name);
1900 if (arg == -1) {
1901 fprintf(stderr,
1902 "lookup %s in %s %d %d\n"
1903 "freevars of %s: %s\n",
1904 PyUnicode_AsUTF8(PyObject_Repr(name)),
1905 PyUnicode_AsUTF8(c->u->u_name),
1906 reftype, arg,
1907 PyUnicode_AsUTF8(co->co_name),
1908 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1909 Py_FatalError("compiler_make_closure()");
1910 }
1911 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 flags |= 0x08;
1914 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001916 ADDOP_LOAD_CONST(c, (PyObject*)co);
1917 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920}
1921
1922static int
1923compiler_decorators(struct compiler *c, asdl_seq* decos)
1924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 if (!decos)
1928 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1931 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1932 }
1933 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934}
1935
1936static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001937compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001939{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001940 /* Push a dict of keyword-only default values.
1941
1942 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1943 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001944 int i;
1945 PyObject *keys = NULL;
1946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1948 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1949 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1950 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001951 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001952 if (!mangled) {
1953 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 if (keys == NULL) {
1956 keys = PyList_New(1);
1957 if (keys == NULL) {
1958 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001959 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 }
1961 PyList_SET_ITEM(keys, 0, mangled);
1962 }
1963 else {
1964 int res = PyList_Append(keys, mangled);
1965 Py_DECREF(mangled);
1966 if (res == -1) {
1967 goto error;
1968 }
1969 }
1970 if (!compiler_visit_expr(c, default_)) {
1971 goto error;
1972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 }
1974 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001975 if (keys != NULL) {
1976 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1977 PyObject *keys_tuple = PyList_AsTuple(keys);
1978 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001979 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001981 assert(default_count > 0);
1982 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 }
1984 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001985 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 }
1987
1988error:
1989 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001991}
1992
1993static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001994compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1995{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001996 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001997 return 1;
1998}
1999
2000static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002001compiler_visit_argannotation(struct compiler *c, identifier id,
2002 expr_ty annotation, PyObject *names)
2003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002005 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002006 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2007 VISIT(c, annexpr, annotation)
2008 }
2009 else {
2010 VISIT(c, expr, annotation);
2011 }
Victor Stinner065efc32014-02-18 22:07:56 +01002012 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002013 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002014 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002015 if (PyList_Append(names, mangled) < 0) {
2016 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002017 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002018 }
2019 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002021 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002022}
2023
2024static int
2025compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2026 PyObject *names)
2027{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002028 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 for (i = 0; i < asdl_seq_LEN(args); i++) {
2030 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002031 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 c,
2033 arg->arg,
2034 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002035 names))
2036 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002038 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002039}
2040
2041static int
2042compiler_visit_annotations(struct compiler *c, arguments_ty args,
2043 expr_ty returns)
2044{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002045 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002046 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002047
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002048 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 */
2050 static identifier return_str;
2051 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002052 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 names = PyList_New(0);
2054 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002055 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002056
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002059 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2060 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002061 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002062 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002063 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002065 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002067 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002068 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002069 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 if (!return_str) {
2073 return_str = PyUnicode_InternFromString("return");
2074 if (!return_str)
2075 goto error;
2076 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002077 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 goto error;
2079 }
2080
2081 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002083 PyObject *keytuple = PyList_AsTuple(names);
2084 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002085 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002086 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002087 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002089 else {
2090 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002091 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002092 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002093
2094error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002096 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002097}
2098
2099static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002100compiler_visit_defaults(struct compiler *c, arguments_ty args)
2101{
2102 VISIT_SEQ(c, expr, args->defaults);
2103 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2104 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105}
2106
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002107static Py_ssize_t
2108compiler_default_arguments(struct compiler *c, arguments_ty args)
2109{
2110 Py_ssize_t funcflags = 0;
2111 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002112 if (!compiler_visit_defaults(c, args))
2113 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002114 funcflags |= 0x01;
2115 }
2116 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002117 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002119 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002120 return -1;
2121 }
2122 else if (res > 0) {
2123 funcflags |= 0x02;
2124 }
2125 }
2126 return funcflags;
2127}
2128
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129static int
Yury Selivanov75445082015-05-11 22:57:16 -04002130compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002133 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002134 arguments_ty args;
2135 expr_ty returns;
2136 identifier name;
2137 asdl_seq* decos;
2138 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002139 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002140 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002141 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002142 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143
Yury Selivanov75445082015-05-11 22:57:16 -04002144 if (is_async) {
2145 assert(s->kind == AsyncFunctionDef_kind);
2146
2147 args = s->v.AsyncFunctionDef.args;
2148 returns = s->v.AsyncFunctionDef.returns;
2149 decos = s->v.AsyncFunctionDef.decorator_list;
2150 name = s->v.AsyncFunctionDef.name;
2151 body = s->v.AsyncFunctionDef.body;
2152
2153 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2154 } else {
2155 assert(s->kind == FunctionDef_kind);
2156
2157 args = s->v.FunctionDef.args;
2158 returns = s->v.FunctionDef.returns;
2159 decos = s->v.FunctionDef.decorator_list;
2160 name = s->v.FunctionDef.name;
2161 body = s->v.FunctionDef.body;
2162
2163 scope_type = COMPILER_SCOPE_FUNCTION;
2164 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (!compiler_decorators(c, decos))
2167 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002168
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002169 firstlineno = s->lineno;
2170 if (asdl_seq_LEN(decos)) {
2171 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2172 }
2173
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002174 funcflags = compiler_default_arguments(c, args);
2175 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002177 }
2178
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002179 annotations = compiler_visit_annotations(c, args, returns);
2180 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002181 return 0;
2182 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002183 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002184 funcflags |= 0x04;
2185 }
2186
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002187 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002188 return 0;
2189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190
INADA Naokicb41b272017-02-23 00:31:59 +09002191 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002192 if (c->c_optimize < 2) {
2193 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002194 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002195 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 compiler_exit_scope(c);
2197 return 0;
2198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002201 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002203 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002205 qualname = c->u->u_qualname;
2206 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002208 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002209 Py_XDECREF(qualname);
2210 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002214 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002215 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* decorators */
2219 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2220 ADDOP_I(c, CALL_FUNCTION, 1);
2221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222
Yury Selivanov75445082015-05-11 22:57:16 -04002223 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224}
2225
2226static int
2227compiler_class(struct compiler *c, stmt_ty s)
2228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyCodeObject *co;
2230 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002231 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (!compiler_decorators(c, decos))
2235 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002236
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002237 firstlineno = s->lineno;
2238 if (asdl_seq_LEN(decos)) {
2239 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2240 }
2241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* ultimately generate code for:
2243 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2244 where:
2245 <func> is a function/closure created from the class body;
2246 it has a single argument (__locals__) where the dict
2247 (or MutableSequence) representing the locals is passed
2248 <name> is the class name
2249 <bases> is the positional arguments and *varargs argument
2250 <keywords> is the keyword arguments and **kwds argument
2251 This borrows from compiler_call.
2252 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002255 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002256 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return 0;
2258 /* this block represents what we do in the new scope */
2259 {
2260 /* use the class name for name mangling */
2261 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002262 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* load (global) __name__ ... */
2264 str = PyUnicode_InternFromString("__name__");
2265 if (!str || !compiler_nameop(c, str, Load)) {
2266 Py_XDECREF(str);
2267 compiler_exit_scope(c);
2268 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 Py_DECREF(str);
2271 /* ... and store it as __module__ */
2272 str = PyUnicode_InternFromString("__module__");
2273 if (!str || !compiler_nameop(c, str, Store)) {
2274 Py_XDECREF(str);
2275 compiler_exit_scope(c);
2276 return 0;
2277 }
2278 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002279 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002280 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002281 str = PyUnicode_InternFromString("__qualname__");
2282 if (!str || !compiler_nameop(c, str, Store)) {
2283 Py_XDECREF(str);
2284 compiler_exit_scope(c);
2285 return 0;
2286 }
2287 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002289 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_exit_scope(c);
2291 return 0;
2292 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002293 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002294 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002295 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002296 str = PyUnicode_InternFromString("__class__");
2297 if (str == NULL) {
2298 compiler_exit_scope(c);
2299 return 0;
2300 }
2301 i = compiler_lookup_arg(c->u->u_cellvars, str);
2302 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002303 if (i < 0) {
2304 compiler_exit_scope(c);
2305 return 0;
2306 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002307 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002310 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002311 str = PyUnicode_InternFromString("__classcell__");
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 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002319 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002320 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002321 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002322 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002323 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002324 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* create the code object */
2326 co = assemble(c, 1);
2327 }
2328 /* leave the new scope */
2329 compiler_exit_scope(c);
2330 if (co == NULL)
2331 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* 2. load the 'build_class' function */
2334 ADDOP(c, LOAD_BUILD_CLASS);
2335
2336 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002337 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 Py_DECREF(co);
2339
2340 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002341 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342
2343 /* 5. generate the rest of the code for the call */
2344 if (!compiler_call_helper(c, 2,
2345 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002346 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 return 0;
2348
2349 /* 6. apply decorators */
2350 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2351 ADDOP_I(c, CALL_FUNCTION, 1);
2352 }
2353
2354 /* 7. store into <name> */
2355 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2356 return 0;
2357 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358}
2359
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002360/* Return 0 if the expression is a constant value except named singletons.
2361 Return 1 otherwise. */
2362static int
2363check_is_arg(expr_ty e)
2364{
2365 if (e->kind != Constant_kind) {
2366 return 1;
2367 }
2368 PyObject *value = e->v.Constant.value;
2369 return (value == Py_None
2370 || value == Py_False
2371 || value == Py_True
2372 || value == Py_Ellipsis);
2373}
2374
2375/* Check operands of identity chacks ("is" and "is not").
2376 Emit a warning if any operand is a constant except named singletons.
2377 Return 0 on error.
2378 */
2379static int
2380check_compare(struct compiler *c, expr_ty e)
2381{
2382 Py_ssize_t i, n;
2383 int left = check_is_arg(e->v.Compare.left);
2384 n = asdl_seq_LEN(e->v.Compare.ops);
2385 for (i = 0; i < n; i++) {
2386 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2387 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2388 if (op == Is || op == IsNot) {
2389 if (!right || !left) {
2390 const char *msg = (op == Is)
2391 ? "\"is\" with a literal. Did you mean \"==\"?"
2392 : "\"is not\" with a literal. Did you mean \"!=\"?";
2393 return compiler_warn(c, msg);
2394 }
2395 }
2396 left = right;
2397 }
2398 return 1;
2399}
2400
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002402cmpop(cmpop_ty op)
2403{
2404 switch (op) {
2405 case Eq:
2406 return PyCmp_EQ;
2407 case NotEq:
2408 return PyCmp_NE;
2409 case Lt:
2410 return PyCmp_LT;
2411 case LtE:
2412 return PyCmp_LE;
2413 case Gt:
2414 return PyCmp_GT;
2415 case GtE:
2416 return PyCmp_GE;
2417 case Is:
2418 return PyCmp_IS;
2419 case IsNot:
2420 return PyCmp_IS_NOT;
2421 case In:
2422 return PyCmp_IN;
2423 case NotIn:
2424 return PyCmp_NOT_IN;
2425 default:
2426 return PyCmp_BAD;
2427 }
2428}
2429
2430static int
2431compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2432{
2433 switch (e->kind) {
2434 case UnaryOp_kind:
2435 if (e->v.UnaryOp.op == Not)
2436 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2437 /* fallback to general implementation */
2438 break;
2439 case BoolOp_kind: {
2440 asdl_seq *s = e->v.BoolOp.values;
2441 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2442 assert(n >= 0);
2443 int cond2 = e->v.BoolOp.op == Or;
2444 basicblock *next2 = next;
2445 if (!cond2 != !cond) {
2446 next2 = compiler_new_block(c);
2447 if (next2 == NULL)
2448 return 0;
2449 }
2450 for (i = 0; i < n; ++i) {
2451 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2452 return 0;
2453 }
2454 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2455 return 0;
2456 if (next2 != next)
2457 compiler_use_next_block(c, next2);
2458 return 1;
2459 }
2460 case IfExp_kind: {
2461 basicblock *end, *next2;
2462 end = compiler_new_block(c);
2463 if (end == NULL)
2464 return 0;
2465 next2 = compiler_new_block(c);
2466 if (next2 == NULL)
2467 return 0;
2468 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2469 return 0;
2470 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2471 return 0;
2472 ADDOP_JREL(c, JUMP_FORWARD, end);
2473 compiler_use_next_block(c, next2);
2474 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2475 return 0;
2476 compiler_use_next_block(c, end);
2477 return 1;
2478 }
2479 case Compare_kind: {
2480 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2481 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002482 if (!check_compare(c, e)) {
2483 return 0;
2484 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 basicblock *cleanup = compiler_new_block(c);
2486 if (cleanup == NULL)
2487 return 0;
2488 VISIT(c, expr, e->v.Compare.left);
2489 for (i = 0; i < n; i++) {
2490 VISIT(c, expr,
2491 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2492 ADDOP(c, DUP_TOP);
2493 ADDOP(c, ROT_THREE);
2494 ADDOP_I(c, COMPARE_OP,
2495 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2496 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2497 NEXT_BLOCK(c);
2498 }
2499 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2500 ADDOP_I(c, COMPARE_OP,
2501 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2502 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2503 basicblock *end = compiler_new_block(c);
2504 if (end == NULL)
2505 return 0;
2506 ADDOP_JREL(c, JUMP_FORWARD, end);
2507 compiler_use_next_block(c, cleanup);
2508 ADDOP(c, POP_TOP);
2509 if (!cond) {
2510 ADDOP_JREL(c, JUMP_FORWARD, next);
2511 }
2512 compiler_use_next_block(c, end);
2513 return 1;
2514 }
2515 /* fallback to general implementation */
2516 break;
2517 }
2518 default:
2519 /* fallback to general implementation */
2520 break;
2521 }
2522
2523 /* general implementation */
2524 VISIT(c, expr, e);
2525 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2526 return 1;
2527}
2528
2529static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002530compiler_ifexp(struct compiler *c, expr_ty e)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 basicblock *end, *next;
2533
2534 assert(e->kind == IfExp_kind);
2535 end = compiler_new_block(c);
2536 if (end == NULL)
2537 return 0;
2538 next = compiler_new_block(c);
2539 if (next == NULL)
2540 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002541 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2542 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 VISIT(c, expr, e->v.IfExp.body);
2544 ADDOP_JREL(c, JUMP_FORWARD, end);
2545 compiler_use_next_block(c, next);
2546 VISIT(c, expr, e->v.IfExp.orelse);
2547 compiler_use_next_block(c, end);
2548 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002549}
2550
2551static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552compiler_lambda(struct compiler *c, expr_ty e)
2553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002555 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002557 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 arguments_ty args = e->v.Lambda.args;
2559 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (!name) {
2562 name = PyUnicode_InternFromString("<lambda>");
2563 if (!name)
2564 return 0;
2565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002567 funcflags = compiler_default_arguments(c, args);
2568 if (funcflags == -1) {
2569 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002571
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002572 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002573 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 /* Make None the first constant, so the lambda can't have a
2577 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002578 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002582 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2584 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2585 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002586 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 }
2588 else {
2589 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002590 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002592 qualname = c->u->u_qualname;
2593 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002595 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002598 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002599 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 Py_DECREF(co);
2601
2602 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603}
2604
2605static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606compiler_if(struct compiler *c, stmt_ty s)
2607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 basicblock *end, *next;
2609 int constant;
2610 assert(s->kind == If_kind);
2611 end = compiler_new_block(c);
2612 if (end == NULL)
2613 return 0;
2614
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002615 constant = expr_constant(s->v.If.test);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002616 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 * constant = 1: "if 1", "if 2", ...
2618 * constant = -1: rest */
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002619 if (constant == 0) {
2620 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 VISIT_SEQ(c, stmt, s->v.If.body);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002622 END_DO_NOT_EMIT_BYTECODE
2623 if (s->v.If.orelse) {
2624 VISIT_SEQ(c, stmt, s->v.If.orelse);
2625 }
2626 } else if (constant == 1) {
2627 VISIT_SEQ(c, stmt, s->v.If.body);
2628 if (s->v.If.orelse) {
2629 BEGIN_DO_NOT_EMIT_BYTECODE
2630 VISIT_SEQ(c, stmt, s->v.If.orelse);
2631 END_DO_NOT_EMIT_BYTECODE
2632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002634 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 next = compiler_new_block(c);
2636 if (next == NULL)
2637 return 0;
2638 }
2639 else
2640 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002641 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2642 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002644 if (asdl_seq_LEN(s->v.If.orelse)) {
2645 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 compiler_use_next_block(c, next);
2647 VISIT_SEQ(c, stmt, s->v.If.orelse);
2648 }
2649 }
2650 compiler_use_next_block(c, end);
2651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652}
2653
2654static int
2655compiler_for(struct compiler *c, stmt_ty s)
2656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 start = compiler_new_block(c);
2660 cleanup = compiler_new_block(c);
2661 end = compiler_new_block(c);
2662 if (start == NULL || end == NULL || cleanup == NULL)
2663 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664
2665 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 VISIT(c, expr, s->v.For.iter);
2669 ADDOP(c, GET_ITER);
2670 compiler_use_next_block(c, start);
2671 ADDOP_JREL(c, FOR_ITER, cleanup);
2672 VISIT(c, expr, s->v.For.target);
2673 VISIT_SEQ(c, stmt, s->v.For.body);
2674 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2675 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002676
2677 compiler_pop_fblock(c, FOR_LOOP, start);
2678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 VISIT_SEQ(c, stmt, s->v.For.orelse);
2680 compiler_use_next_block(c, end);
2681 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682}
2683
Yury Selivanov75445082015-05-11 22:57:16 -04002684
2685static int
2686compiler_async_for(struct compiler *c, stmt_ty s)
2687{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002688 basicblock *start, *except, *end;
Miss Islington (bot)f7e32fc2020-03-14 21:46:26 -07002689 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002690 c->u->u_ste->ste_coroutine = 1;
2691 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002692 return compiler_error(c, "'async for' outside async function");
2693 }
2694
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002695 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002696 except = compiler_new_block(c);
2697 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002698
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002699 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002700 return 0;
2701
2702 VISIT(c, expr, s->v.AsyncFor.iter);
2703 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002704
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002705 compiler_use_next_block(c, start);
2706 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2707 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002708
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709 /* SETUP_FINALLY to guard the __anext__ call */
2710 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002711 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002712 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002713 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002714 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002715
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002716 /* Success block for __anext__ */
2717 VISIT(c, expr, s->v.AsyncFor.target);
2718 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2719 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2720
2721 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002722
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002723 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002724 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002725 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002726
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002727 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002728 VISIT_SEQ(c, stmt, s->v.For.orelse);
2729
2730 compiler_use_next_block(c, end);
2731
2732 return 1;
2733}
2734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735static int
2736compiler_while(struct compiler *c, stmt_ty s)
2737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002739 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 if (constant == 0) {
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002742 BEGIN_DO_NOT_EMIT_BYTECODE
Miss Skeleton (bot)dcb338e2019-10-30 05:11:41 -07002743 // Push a dummy block so the VISIT_SEQ knows that we are
2744 // inside a while loop so it can correctly evaluate syntax
2745 // errors.
2746 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL)) {
2747 return 0;
2748 }
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002749 VISIT_SEQ(c, stmt, s->v.While.body);
Miss Skeleton (bot)dcb338e2019-10-30 05:11:41 -07002750 // Remove the dummy block now that is not needed.
2751 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002752 END_DO_NOT_EMIT_BYTECODE
2753 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 VISIT_SEQ(c, stmt, s->v.While.orelse);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002755 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 return 1;
2757 }
2758 loop = compiler_new_block(c);
2759 end = compiler_new_block(c);
2760 if (constant == -1) {
2761 anchor = compiler_new_block(c);
2762 if (anchor == NULL)
2763 return 0;
2764 }
2765 if (loop == NULL || end == NULL)
2766 return 0;
2767 if (s->v.While.orelse) {
2768 orelse = compiler_new_block(c);
2769 if (orelse == NULL)
2770 return 0;
2771 }
2772 else
2773 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002776 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return 0;
2778 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002779 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2780 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 }
2782 VISIT_SEQ(c, stmt, s->v.While.body);
2783 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* XXX should the two POP instructions be in a separate block
2786 if there is no else clause ?
2787 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002789 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002791 compiler_pop_fblock(c, WHILE_LOOP, loop);
2792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 if (orelse != NULL) /* what if orelse is just pass? */
2794 VISIT_SEQ(c, stmt, s->v.While.orelse);
2795 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798}
2799
2800static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002804 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002805 if (c->u->u_ste->ste_type != FunctionBlock)
2806 return compiler_error(c, "'return' outside function");
2807 if (s->v.Return.value != NULL &&
2808 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2809 {
2810 return compiler_error(
2811 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002813 if (preserve_tos) {
2814 VISIT(c, expr, s->v.Return.value);
2815 }
2816 for (int depth = c->u->u_nfblocks; depth--;) {
2817 struct fblockinfo *info = &c->u->u_fblock[depth];
2818
2819 if (!compiler_unwind_fblock(c, info, preserve_tos))
2820 return 0;
2821 }
2822 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002823 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002824 }
2825 else if (!preserve_tos) {
2826 VISIT(c, expr, s->v.Return.value);
2827 }
2828 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831}
2832
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002833static int
2834compiler_break(struct compiler *c)
2835{
2836 for (int depth = c->u->u_nfblocks; depth--;) {
2837 struct fblockinfo *info = &c->u->u_fblock[depth];
2838
2839 if (!compiler_unwind_fblock(c, info, 0))
2840 return 0;
2841 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2842 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2843 return 1;
2844 }
2845 }
2846 return compiler_error(c, "'break' outside loop");
2847}
2848
2849static int
2850compiler_continue(struct compiler *c)
2851{
2852 for (int depth = c->u->u_nfblocks; depth--;) {
2853 struct fblockinfo *info = &c->u->u_fblock[depth];
2854
2855 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2856 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2857 return 1;
2858 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 if (!compiler_unwind_fblock(c, info, 0))
2860 return 0;
2861 }
2862 return compiler_error(c, "'continue' not properly in loop");
2863}
2864
2865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867
2868 SETUP_FINALLY L
2869 <code for body>
2870 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002871 BEGIN_FINALLY
2872 L:
2873 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 END_FINALLY
2875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876 The special instructions use the block stack. Each block
2877 stack entry contains the instruction that created it (here
2878 SETUP_FINALLY), the level of the value stack at the time the
2879 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 Pushes the current value stack level and the label
2883 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 Pops en entry from the block stack.
2886 BEGIN_FINALLY
2887 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002889 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2890 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002893 when a SETUP_FINALLY entry is found, the raised and the caught
2894 exceptions are pushed onto the value stack (and the exception
2895 condition is cleared), and the interpreter jumps to the label
2896 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897*/
2898
2899static int
2900compiler_try_finally(struct compiler *c, stmt_ty s)
2901{
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002902 basicblock *start, *newcurblock, *body, *end;
2903 int break_finally = 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 body = compiler_new_block(c);
2906 end = compiler_new_block(c);
2907 if (body == NULL || end == NULL)
2908 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002910 start = c->u->u_curblock;
2911
2912 /* `finally` block. Compile it first to determine if any of "break",
2913 "continue" or "return" are used in it. */
2914 compiler_use_next_block(c, end);
2915 if (!compiler_push_fblock(c, FINALLY_END, end, end))
2916 return 0;
2917 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2918 ADDOP(c, END_FINALLY);
2919 break_finally = (c->u->u_fblock[c->u->u_nfblocks - 1].fb_exit == NULL);
2920 if (break_finally) {
2921 /* Pops a placeholder. See below */
2922 ADDOP(c, POP_TOP);
2923 }
2924 compiler_pop_fblock(c, FINALLY_END, end);
2925
2926 newcurblock = c->u->u_curblock;
2927 c->u->u_curblock = start;
2928 start->b_next = NULL;
2929
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002930 /* `try` block */
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002931 c->u->u_lineno_set = 0;
2932 c->u->u_lineno = s->lineno;
2933 c->u->u_col_offset = s->col_offset;
2934 if (break_finally) {
2935 /* Pushes a placeholder for the value of "return" in the "try" block
2936 to balance the stack for "break", "continue" and "return" in
2937 the "finally" block. */
2938 ADDOP_LOAD_CONST(c, Py_None);
2939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 ADDOP_JREL(c, SETUP_FINALLY, end);
2941 compiler_use_next_block(c, body);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002942 if (!compiler_push_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002944 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2945 if (!compiler_try_except(c, s))
2946 return 0;
2947 }
2948 else {
2949 VISIT_SEQ(c, stmt, s->v.Try.body);
2950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002952 ADDOP(c, BEGIN_FINALLY);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002953 compiler_pop_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002955 c->u->u_curblock->b_next = end;
2956 c->u->u_curblock = newcurblock;
2957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959}
2960
2961/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002962 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 (The contents of the value stack is shown in [], with the top
2964 at the right; 'tb' is trace-back info, 'val' the exception's
2965 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966
2967 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002968 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 [] <code for S>
2970 [] POP_BLOCK
2971 [] JUMP_FORWARD L0
2972
2973 [tb, val, exc] L1: DUP )
2974 [tb, val, exc, exc] <evaluate E1> )
2975 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2976 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2977 [tb, val, exc] POP
2978 [tb, val] <assign to V1> (or POP if no V1)
2979 [tb] POP
2980 [] <code for S1>
2981 JUMP_FORWARD L0
2982
2983 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 .............................etc.......................
2985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2987
2988 [] L0: <next statement>
2989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 Of course, parts are not generated if Vi or Ei is not present.
2991*/
2992static int
2993compiler_try_except(struct compiler *c, stmt_ty s)
2994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002996 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 body = compiler_new_block(c);
2999 except = compiler_new_block(c);
3000 orelse = compiler_new_block(c);
3001 end = compiler_new_block(c);
3002 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3003 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003004 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003006 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003008 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 ADDOP(c, POP_BLOCK);
3010 compiler_pop_fblock(c, EXCEPT, body);
3011 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003012 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 compiler_use_next_block(c, except);
3014 for (i = 0; i < n; i++) {
3015 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003016 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 if (!handler->v.ExceptHandler.type && i < n-1)
3018 return compiler_error(c, "default 'except:' must be last");
3019 c->u->u_lineno_set = 0;
3020 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003021 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 except = compiler_new_block(c);
3023 if (except == NULL)
3024 return 0;
3025 if (handler->v.ExceptHandler.type) {
3026 ADDOP(c, DUP_TOP);
3027 VISIT(c, expr, handler->v.ExceptHandler.type);
3028 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3029 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3030 }
3031 ADDOP(c, POP_TOP);
3032 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003033 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003034
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003035 cleanup_end = compiler_new_block(c);
3036 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003037 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003038 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003039 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003040
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003041 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3042 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003044 /*
3045 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003046 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003048 try:
3049 # body
3050 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003051 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003052 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003053 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003055 /* second try: */
3056 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3057 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003058 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 /* second # body */
3062 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
3063 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003064 ADDOP(c, BEGIN_FINALLY);
3065 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003069 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003072 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003073 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02003078 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
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);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003091 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, 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);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003095 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
3097 ADDOP_JREL(c, JUMP_FORWARD, end);
3098 compiler_use_next_block(c, except);
3099 }
3100 ADDOP(c, END_FINALLY);
3101 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 static PyObject *assertion_error = NULL;
3269 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Georg Brandl8334fd92010-12-04 10:26:46 +00003271 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 return 1;
3273 if (assertion_error == NULL) {
3274 assertion_error = PyUnicode_InternFromString("AssertionError");
3275 if (assertion_error == NULL)
3276 return 0;
3277 }
3278 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003279 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3280 {
3281 if (!compiler_warn(c, "assertion is always true, "
3282 "perhaps remove parentheses?"))
3283 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003284 return 0;
3285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 end = compiler_new_block(c);
3288 if (end == NULL)
3289 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003290 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3291 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3293 if (s->v.Assert.msg) {
3294 VISIT(c, expr, s->v.Assert.msg);
3295 ADDOP_I(c, CALL_FUNCTION, 1);
3296 }
3297 ADDOP_I(c, RAISE_VARARGS, 1);
3298 compiler_use_next_block(c, end);
3299 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300}
3301
3302static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003303compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3304{
3305 if (c->c_interactive && c->c_nestlevel <= 1) {
3306 VISIT(c, expr, value);
3307 ADDOP(c, PRINT_EXPR);
3308 return 1;
3309 }
3310
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003311 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003312 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003313 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003314 }
3315
3316 VISIT(c, expr, value);
3317 ADDOP(c, POP_TOP);
3318 return 1;
3319}
3320
3321static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322compiler_visit_stmt(struct compiler *c, stmt_ty s)
3323{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003324 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 /* Always assign a lineno to the next instruction for a stmt. */
3327 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003328 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 switch (s->kind) {
3332 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003333 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 case ClassDef_kind:
3335 return compiler_class(c, s);
3336 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003337 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 case Delete_kind:
3339 VISIT_SEQ(c, expr, s->v.Delete.targets)
3340 break;
3341 case Assign_kind:
3342 n = asdl_seq_LEN(s->v.Assign.targets);
3343 VISIT(c, expr, s->v.Assign.value);
3344 for (i = 0; i < n; i++) {
3345 if (i < n - 1)
3346 ADDOP(c, DUP_TOP);
3347 VISIT(c, expr,
3348 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3349 }
3350 break;
3351 case AugAssign_kind:
3352 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003353 case AnnAssign_kind:
3354 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case For_kind:
3356 return compiler_for(c, s);
3357 case While_kind:
3358 return compiler_while(c, s);
3359 case If_kind:
3360 return compiler_if(c, s);
3361 case Raise_kind:
3362 n = 0;
3363 if (s->v.Raise.exc) {
3364 VISIT(c, expr, s->v.Raise.exc);
3365 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003366 if (s->v.Raise.cause) {
3367 VISIT(c, expr, s->v.Raise.cause);
3368 n++;
3369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003371 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003373 case Try_kind:
3374 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 case Assert_kind:
3376 return compiler_assert(c, s);
3377 case Import_kind:
3378 return compiler_import(c, s);
3379 case ImportFrom_kind:
3380 return compiler_from_import(c, s);
3381 case Global_kind:
3382 case Nonlocal_kind:
3383 break;
3384 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003385 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 case Pass_kind:
3387 break;
3388 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003389 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 case Continue_kind:
3391 return compiler_continue(c);
3392 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003393 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003394 case AsyncFunctionDef_kind:
3395 return compiler_function(c, s, 1);
3396 case AsyncWith_kind:
3397 return compiler_async_with(c, s, 0);
3398 case AsyncFor_kind:
3399 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 }
Yury Selivanov75445082015-05-11 22:57:16 -04003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403}
3404
3405static int
3406unaryop(unaryop_ty op)
3407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 switch (op) {
3409 case Invert:
3410 return UNARY_INVERT;
3411 case Not:
3412 return UNARY_NOT;
3413 case UAdd:
3414 return UNARY_POSITIVE;
3415 case USub:
3416 return UNARY_NEGATIVE;
3417 default:
3418 PyErr_Format(PyExc_SystemError,
3419 "unary op %d should not be possible", op);
3420 return 0;
3421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422}
3423
3424static int
3425binop(struct compiler *c, operator_ty op)
3426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 switch (op) {
3428 case Add:
3429 return BINARY_ADD;
3430 case Sub:
3431 return BINARY_SUBTRACT;
3432 case Mult:
3433 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003434 case MatMult:
3435 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 case Div:
3437 return BINARY_TRUE_DIVIDE;
3438 case Mod:
3439 return BINARY_MODULO;
3440 case Pow:
3441 return BINARY_POWER;
3442 case LShift:
3443 return BINARY_LSHIFT;
3444 case RShift:
3445 return BINARY_RSHIFT;
3446 case BitOr:
3447 return BINARY_OR;
3448 case BitXor:
3449 return BINARY_XOR;
3450 case BitAnd:
3451 return BINARY_AND;
3452 case FloorDiv:
3453 return BINARY_FLOOR_DIVIDE;
3454 default:
3455 PyErr_Format(PyExc_SystemError,
3456 "binary op %d should not be possible", op);
3457 return 0;
3458 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459}
3460
3461static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462inplace_binop(struct compiler *c, operator_ty op)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 switch (op) {
3465 case Add:
3466 return INPLACE_ADD;
3467 case Sub:
3468 return INPLACE_SUBTRACT;
3469 case Mult:
3470 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003471 case MatMult:
3472 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 case Div:
3474 return INPLACE_TRUE_DIVIDE;
3475 case Mod:
3476 return INPLACE_MODULO;
3477 case Pow:
3478 return INPLACE_POWER;
3479 case LShift:
3480 return INPLACE_LSHIFT;
3481 case RShift:
3482 return INPLACE_RSHIFT;
3483 case BitOr:
3484 return INPLACE_OR;
3485 case BitXor:
3486 return INPLACE_XOR;
3487 case BitAnd:
3488 return INPLACE_AND;
3489 case FloorDiv:
3490 return INPLACE_FLOOR_DIVIDE;
3491 default:
3492 PyErr_Format(PyExc_SystemError,
3493 "inplace binary op %d should not be possible", op);
3494 return 0;
3495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496}
3497
3498static int
3499compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3500{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003501 int op, scope;
3502 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 PyObject *dict = c->u->u_names;
3506 PyObject *mangled;
3507 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003509 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3510 !_PyUnicode_EqualToASCIIString(name, "True") &&
3511 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003512
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003513 mangled = _Py_Mangle(c->u->u_private, name);
3514 if (!mangled)
3515 return 0;
3516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 op = 0;
3518 optype = OP_NAME;
3519 scope = PyST_GetScope(c->u->u_ste, mangled);
3520 switch (scope) {
3521 case FREE:
3522 dict = c->u->u_freevars;
3523 optype = OP_DEREF;
3524 break;
3525 case CELL:
3526 dict = c->u->u_cellvars;
3527 optype = OP_DEREF;
3528 break;
3529 case LOCAL:
3530 if (c->u->u_ste->ste_type == FunctionBlock)
3531 optype = OP_FAST;
3532 break;
3533 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003534 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 optype = OP_GLOBAL;
3536 break;
3537 case GLOBAL_EXPLICIT:
3538 optype = OP_GLOBAL;
3539 break;
3540 default:
3541 /* scope can be 0 */
3542 break;
3543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003546 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 switch (optype) {
3549 case OP_DEREF:
3550 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003551 case Load:
3552 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3553 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003554 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003555 op = STORE_DEREF;
3556 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 case AugLoad:
3558 case AugStore:
3559 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003560 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 case Param:
3562 default:
3563 PyErr_SetString(PyExc_SystemError,
3564 "param invalid for deref variable");
3565 return 0;
3566 }
3567 break;
3568 case OP_FAST:
3569 switch (ctx) {
3570 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003571 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003572 op = STORE_FAST;
3573 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 case Del: op = DELETE_FAST; break;
3575 case AugLoad:
3576 case AugStore:
3577 break;
3578 case Param:
3579 default:
3580 PyErr_SetString(PyExc_SystemError,
3581 "param invalid for local variable");
3582 return 0;
3583 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003584 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 return 1;
3586 case OP_GLOBAL:
3587 switch (ctx) {
3588 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003589 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003590 op = STORE_GLOBAL;
3591 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 case Del: op = DELETE_GLOBAL; break;
3593 case AugLoad:
3594 case AugStore:
3595 break;
3596 case Param:
3597 default:
3598 PyErr_SetString(PyExc_SystemError,
3599 "param invalid for global variable");
3600 return 0;
3601 }
3602 break;
3603 case OP_NAME:
3604 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003605 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003606 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003607 op = STORE_NAME;
3608 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 case Del: op = DELETE_NAME; break;
3610 case AugLoad:
3611 case AugStore:
3612 break;
3613 case Param:
3614 default:
3615 PyErr_SetString(PyExc_SystemError,
3616 "param invalid for name variable");
3617 return 0;
3618 }
3619 break;
3620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 assert(op);
3623 arg = compiler_add_o(c, dict, mangled);
3624 Py_DECREF(mangled);
3625 if (arg < 0)
3626 return 0;
3627 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628}
3629
3630static int
3631compiler_boolop(struct compiler *c, expr_ty e)
3632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003634 int jumpi;
3635 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 assert(e->kind == BoolOp_kind);
3639 if (e->v.BoolOp.op == And)
3640 jumpi = JUMP_IF_FALSE_OR_POP;
3641 else
3642 jumpi = JUMP_IF_TRUE_OR_POP;
3643 end = compiler_new_block(c);
3644 if (end == NULL)
3645 return 0;
3646 s = e->v.BoolOp.values;
3647 n = asdl_seq_LEN(s) - 1;
3648 assert(n >= 0);
3649 for (i = 0; i < n; ++i) {
3650 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3651 ADDOP_JABS(c, jumpi, end);
3652 }
3653 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3654 compiler_use_next_block(c, end);
3655 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656}
3657
3658static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003659starunpack_helper(struct compiler *c, asdl_seq *elts,
3660 int single_op, int inner_op, int outer_op)
3661{
3662 Py_ssize_t n = asdl_seq_LEN(elts);
3663 Py_ssize_t i, nsubitems = 0, nseen = 0;
3664 for (i = 0; i < n; i++) {
3665 expr_ty elt = asdl_seq_GET(elts, i);
3666 if (elt->kind == Starred_kind) {
3667 if (nseen) {
3668 ADDOP_I(c, inner_op, nseen);
3669 nseen = 0;
3670 nsubitems++;
3671 }
3672 VISIT(c, expr, elt->v.Starred.value);
3673 nsubitems++;
3674 }
3675 else {
3676 VISIT(c, expr, elt);
3677 nseen++;
3678 }
3679 }
3680 if (nsubitems) {
3681 if (nseen) {
3682 ADDOP_I(c, inner_op, nseen);
3683 nsubitems++;
3684 }
3685 ADDOP_I(c, outer_op, nsubitems);
3686 }
3687 else
3688 ADDOP_I(c, single_op, nseen);
3689 return 1;
3690}
3691
3692static int
3693assignment_helper(struct compiler *c, asdl_seq *elts)
3694{
3695 Py_ssize_t n = asdl_seq_LEN(elts);
3696 Py_ssize_t i;
3697 int seen_star = 0;
3698 for (i = 0; i < n; i++) {
3699 expr_ty elt = asdl_seq_GET(elts, i);
3700 if (elt->kind == Starred_kind && !seen_star) {
3701 if ((i >= (1 << 8)) ||
3702 (n-i-1 >= (INT_MAX >> 8)))
3703 return compiler_error(c,
3704 "too many expressions in "
3705 "star-unpacking assignment");
3706 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3707 seen_star = 1;
3708 asdl_seq_SET(elts, i, elt->v.Starred.value);
3709 }
3710 else if (elt->kind == Starred_kind) {
3711 return compiler_error(c,
3712 "two starred expressions in assignment");
3713 }
3714 }
3715 if (!seen_star) {
3716 ADDOP_I(c, UNPACK_SEQUENCE, n);
3717 }
3718 VISIT_SEQ(c, expr, elts);
3719 return 1;
3720}
3721
3722static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723compiler_list(struct compiler *c, expr_ty e)
3724{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003726 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 else if (e->v.List.ctx == Load) {
3730 return starunpack_helper(c, elts,
3731 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 else
3734 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736}
3737
3738static int
3739compiler_tuple(struct compiler *c, expr_ty e)
3740{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003741 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003742 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 return assignment_helper(c, elts);
3744 }
3745 else if (e->v.Tuple.ctx == Load) {
3746 return starunpack_helper(c, elts,
3747 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3748 }
3749 else
3750 VISIT_SEQ(c, expr, elts);
3751 return 1;
3752}
3753
3754static int
3755compiler_set(struct compiler *c, expr_ty e)
3756{
3757 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3758 BUILD_SET, BUILD_SET_UNPACK);
3759}
3760
3761static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003762are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3763{
3764 Py_ssize_t i;
3765 for (i = begin; i < end; i++) {
3766 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003767 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003768 return 0;
3769 }
3770 return 1;
3771}
3772
3773static int
3774compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3775{
3776 Py_ssize_t i, n = end - begin;
3777 PyObject *keys, *key;
3778 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3779 for (i = begin; i < end; i++) {
3780 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3781 }
3782 keys = PyTuple_New(n);
3783 if (keys == NULL) {
3784 return 0;
3785 }
3786 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003787 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003788 Py_INCREF(key);
3789 PyTuple_SET_ITEM(keys, i - begin, key);
3790 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003791 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003792 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3793 }
3794 else {
3795 for (i = begin; i < end; i++) {
3796 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3797 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3798 }
3799 ADDOP_I(c, BUILD_MAP, n);
3800 }
3801 return 1;
3802}
3803
3804static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805compiler_dict(struct compiler *c, expr_ty e)
3806{
Victor Stinner976bb402016-03-23 11:36:19 +01003807 Py_ssize_t i, n, elements;
3808 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 int is_unpacking = 0;
3810 n = asdl_seq_LEN(e->v.Dict.values);
3811 containers = 0;
3812 elements = 0;
3813 for (i = 0; i < n; i++) {
3814 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3815 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003816 if (!compiler_subdict(c, e, i - elements, i))
3817 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 containers++;
3819 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821 if (is_unpacking) {
3822 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3823 containers++;
3824 }
3825 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003826 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 }
3828 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003829 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003830 if (!compiler_subdict(c, e, n - elements, n))
3831 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003832 containers++;
3833 }
3834 /* If there is more than one dict, they need to be merged into a new
3835 * dict. If there is one dict and it's an unpacking, then it needs
3836 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003837 if (containers > 1 || is_unpacking) {
3838 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 }
3840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841}
3842
3843static int
3844compiler_compare(struct compiler *c, expr_ty e)
3845{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003846 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003848 if (!check_compare(c, e)) {
3849 return 0;
3850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003852 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3853 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3854 if (n == 0) {
3855 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3856 ADDOP_I(c, COMPARE_OP,
3857 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3858 }
3859 else {
3860 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 if (cleanup == NULL)
3862 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003863 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 VISIT(c, expr,
3865 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003866 ADDOP(c, DUP_TOP);
3867 ADDOP(c, ROT_THREE);
3868 ADDOP_I(c, COMPARE_OP,
3869 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3870 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3871 NEXT_BLOCK(c);
3872 }
3873 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3874 ADDOP_I(c, COMPARE_OP,
3875 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 basicblock *end = compiler_new_block(c);
3877 if (end == NULL)
3878 return 0;
3879 ADDOP_JREL(c, JUMP_FORWARD, end);
3880 compiler_use_next_block(c, cleanup);
3881 ADDOP(c, ROT_TWO);
3882 ADDOP(c, POP_TOP);
3883 compiler_use_next_block(c, end);
3884 }
3885 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886}
3887
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003888static PyTypeObject *
3889infer_type(expr_ty e)
3890{
3891 switch (e->kind) {
3892 case Tuple_kind:
3893 return &PyTuple_Type;
3894 case List_kind:
3895 case ListComp_kind:
3896 return &PyList_Type;
3897 case Dict_kind:
3898 case DictComp_kind:
3899 return &PyDict_Type;
3900 case Set_kind:
3901 case SetComp_kind:
3902 return &PySet_Type;
3903 case GeneratorExp_kind:
3904 return &PyGen_Type;
3905 case Lambda_kind:
3906 return &PyFunction_Type;
3907 case JoinedStr_kind:
3908 case FormattedValue_kind:
3909 return &PyUnicode_Type;
3910 case Constant_kind:
3911 return e->v.Constant.value->ob_type;
3912 default:
3913 return NULL;
3914 }
3915}
3916
3917static int
3918check_caller(struct compiler *c, expr_ty e)
3919{
3920 switch (e->kind) {
3921 case Constant_kind:
3922 case Tuple_kind:
3923 case List_kind:
3924 case ListComp_kind:
3925 case Dict_kind:
3926 case DictComp_kind:
3927 case Set_kind:
3928 case SetComp_kind:
3929 case GeneratorExp_kind:
3930 case JoinedStr_kind:
3931 case FormattedValue_kind:
3932 return compiler_warn(c, "'%.200s' object is not callable; "
3933 "perhaps you missed a comma?",
3934 infer_type(e)->tp_name);
3935 default:
3936 return 1;
3937 }
3938}
3939
3940static int
3941check_subscripter(struct compiler *c, expr_ty e)
3942{
3943 PyObject *v;
3944
3945 switch (e->kind) {
3946 case Constant_kind:
3947 v = e->v.Constant.value;
3948 if (!(v == Py_None || v == Py_Ellipsis ||
3949 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3950 PyAnySet_Check(v)))
3951 {
3952 return 1;
3953 }
3954 /* fall through */
3955 case Set_kind:
3956 case SetComp_kind:
3957 case GeneratorExp_kind:
3958 case Lambda_kind:
3959 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3960 "perhaps you missed a comma?",
3961 infer_type(e)->tp_name);
3962 default:
3963 return 1;
3964 }
3965}
3966
3967static int
3968check_index(struct compiler *c, expr_ty e, slice_ty s)
3969{
3970 PyObject *v;
3971
3972 if (s->kind != Index_kind) {
3973 return 1;
3974 }
3975 PyTypeObject *index_type = infer_type(s->v.Index.value);
3976 if (index_type == NULL
3977 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3978 || index_type == &PySlice_Type) {
3979 return 1;
3980 }
3981
3982 switch (e->kind) {
3983 case Constant_kind:
3984 v = e->v.Constant.value;
3985 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3986 return 1;
3987 }
3988 /* fall through */
3989 case Tuple_kind:
3990 case List_kind:
3991 case ListComp_kind:
3992 case JoinedStr_kind:
3993 case FormattedValue_kind:
3994 return compiler_warn(c, "%.200s indices must be integers or slices, "
3995 "not %.200s; "
3996 "perhaps you missed a comma?",
3997 infer_type(e)->tp_name,
3998 index_type->tp_name);
3999 default:
4000 return 1;
4001 }
4002}
4003
Zackery Spytz97f5de02019-03-22 01:30:32 -06004004// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004006maybe_optimize_method_call(struct compiler *c, expr_ty e)
4007{
4008 Py_ssize_t argsl, i;
4009 expr_ty meth = e->v.Call.func;
4010 asdl_seq *args = e->v.Call.args;
4011
4012 /* Check that the call node is an attribute access, and that
4013 the call doesn't have keyword parameters. */
4014 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4015 asdl_seq_LEN(e->v.Call.keywords))
4016 return -1;
4017
4018 /* Check that there are no *varargs types of arguments. */
4019 argsl = asdl_seq_LEN(args);
4020 for (i = 0; i < argsl; i++) {
4021 expr_ty elt = asdl_seq_GET(args, i);
4022 if (elt->kind == Starred_kind) {
4023 return -1;
4024 }
4025 }
4026
4027 /* Alright, we can optimize the code. */
4028 VISIT(c, expr, meth->v.Attribute.value);
4029 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4030 VISIT_SEQ(c, expr, e->v.Call.args);
4031 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4032 return 1;
4033}
4034
4035static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004036compiler_call(struct compiler *c, expr_ty e)
4037{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004038 int ret = maybe_optimize_method_call(c, e);
4039 if (ret >= 0) {
4040 return ret;
4041 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004042 if (!check_caller(c, e->v.Call.func)) {
4043 return 0;
4044 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 VISIT(c, expr, e->v.Call.func);
4046 return compiler_call_helper(c, 0,
4047 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004048 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004049}
4050
Eric V. Smith235a6f02015-09-19 14:51:32 -04004051static int
4052compiler_joined_str(struct compiler *c, expr_ty e)
4053{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004054 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004055 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4056 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004057 return 1;
4058}
4059
Eric V. Smitha78c7952015-11-03 12:45:05 -05004060/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004061static int
4062compiler_formatted_value(struct compiler *c, expr_ty e)
4063{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004064 /* Our oparg encodes 2 pieces of information: the conversion
4065 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004066
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004067 Convert the conversion char to 3 bits:
4068 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004069 !s : 001 0x1 FVC_STR
4070 !r : 010 0x2 FVC_REPR
4071 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004072
Eric V. Smitha78c7952015-11-03 12:45:05 -05004073 next bit is whether or not we have a format spec:
4074 yes : 100 0x4
4075 no : 000 0x0
4076 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004077
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004078 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004079 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004080
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004081 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004082 VISIT(c, expr, e->v.FormattedValue.value);
4083
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004084 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004085 case 's': oparg = FVC_STR; break;
4086 case 'r': oparg = FVC_REPR; break;
4087 case 'a': oparg = FVC_ASCII; break;
4088 case -1: oparg = FVC_NONE; break;
4089 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004090 PyErr_Format(PyExc_SystemError,
4091 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004092 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004093 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004094 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004095 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004096 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004097 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004098 }
4099
Eric V. Smitha78c7952015-11-03 12:45:05 -05004100 /* And push our opcode and oparg */
4101 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004102
Eric V. Smith235a6f02015-09-19 14:51:32 -04004103 return 1;
4104}
4105
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004106static int
4107compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4108{
4109 Py_ssize_t i, n = end - begin;
4110 keyword_ty kw;
4111 PyObject *keys, *key;
4112 assert(n > 0);
4113 if (n > 1) {
4114 for (i = begin; i < end; i++) {
4115 kw = asdl_seq_GET(keywords, i);
4116 VISIT(c, expr, kw->value);
4117 }
4118 keys = PyTuple_New(n);
4119 if (keys == NULL) {
4120 return 0;
4121 }
4122 for (i = begin; i < end; i++) {
4123 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4124 Py_INCREF(key);
4125 PyTuple_SET_ITEM(keys, i - begin, key);
4126 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004127 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004128 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4129 }
4130 else {
4131 /* a for loop only executes once */
4132 for (i = begin; i < end; i++) {
4133 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004134 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004135 VISIT(c, expr, kw->value);
4136 }
4137 ADDOP_I(c, BUILD_MAP, n);
4138 }
4139 return 1;
4140}
4141
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004142/* shared code between compiler_call and compiler_class */
4143static int
4144compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004145 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004146 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004147 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004148{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004149 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004150 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004151
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004152 /* the number of tuples and dictionaries on the stack */
4153 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4154
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004155 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004156 nkwelts = asdl_seq_LEN(keywords);
4157
4158 for (i = 0; i < nkwelts; i++) {
4159 keyword_ty kw = asdl_seq_GET(keywords, i);
4160 if (kw->arg == NULL) {
4161 mustdictunpack = 1;
4162 break;
4163 }
4164 }
4165
4166 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004167 for (i = 0; i < nelts; i++) {
4168 expr_ty elt = asdl_seq_GET(args, i);
4169 if (elt->kind == Starred_kind) {
4170 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004171 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004172 if (nseen) {
4173 ADDOP_I(c, BUILD_TUPLE, nseen);
4174 nseen = 0;
4175 nsubargs++;
4176 }
4177 VISIT(c, expr, elt->v.Starred.value);
4178 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004179 }
4180 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004181 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004182 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004185
4186 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004187 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004188 if (nseen) {
4189 /* Pack up any trailing positional arguments. */
4190 ADDOP_I(c, BUILD_TUPLE, nseen);
4191 nsubargs++;
4192 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004193 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004194 /* If we ended up with more than one stararg, we need
4195 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004196 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004197 }
4198 else if (nsubargs == 0) {
4199 ADDOP_I(c, BUILD_TUPLE, 0);
4200 }
4201 nseen = 0; /* the number of keyword arguments on the stack following */
4202 for (i = 0; i < nkwelts; i++) {
4203 keyword_ty kw = asdl_seq_GET(keywords, i);
4204 if (kw->arg == NULL) {
4205 /* A keyword argument unpacking. */
4206 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004207 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4208 return 0;
4209 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004210 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004211 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004212 VISIT(c, expr, kw->value);
4213 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004214 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004215 else {
4216 nseen++;
4217 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004218 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004219 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004220 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004221 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004222 return 0;
4223 nsubkwargs++;
4224 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004225 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004226 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004227 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004228 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4230 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004232 else if (nkwelts) {
4233 PyObject *names;
4234 VISIT_SEQ(c, keyword, keywords);
4235 names = PyTuple_New(nkwelts);
4236 if (names == NULL) {
4237 return 0;
4238 }
4239 for (i = 0; i < nkwelts; i++) {
4240 keyword_ty kw = asdl_seq_GET(keywords, i);
4241 Py_INCREF(kw->arg);
4242 PyTuple_SET_ITEM(names, i, kw->arg);
4243 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004244 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004245 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4246 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004248 else {
4249 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4250 return 1;
4251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252}
4253
Nick Coghlan650f0d02007-04-15 12:05:43 +00004254
4255/* List and set comprehensions and generator expressions work by creating a
4256 nested function to perform the actual iteration. This means that the
4257 iteration variables don't leak into the current scope.
4258 The defined function is called immediately following its definition, with the
4259 result of that call being the result of the expression.
4260 The LC/SC version returns the populated container, while the GE version is
4261 flagged in symtable.c as a generator, so it returns the generator object
4262 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004263
4264 Possible cleanups:
4265 - iterate over the generator sequence instead of using recursion
4266*/
4267
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270compiler_comprehension_generator(struct compiler *c,
4271 asdl_seq *generators, int gen_index,
4272 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004273{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004274 comprehension_ty gen;
4275 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4276 if (gen->is_async) {
4277 return compiler_async_comprehension_generator(
4278 c, generators, gen_index, elt, val, type);
4279 } else {
4280 return compiler_sync_comprehension_generator(
4281 c, generators, gen_index, elt, val, type);
4282 }
4283}
4284
4285static int
4286compiler_sync_comprehension_generator(struct compiler *c,
4287 asdl_seq *generators, int gen_index,
4288 expr_ty elt, expr_ty val, int type)
4289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 /* generate code for the iterator, then each of the ifs,
4291 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 comprehension_ty gen;
4294 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004295 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 start = compiler_new_block(c);
4298 skip = compiler_new_block(c);
4299 if_cleanup = compiler_new_block(c);
4300 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4303 anchor == NULL)
4304 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 if (gen_index == 0) {
4309 /* Receive outermost iter as an implicit argument */
4310 c->u->u_argcount = 1;
4311 ADDOP_I(c, LOAD_FAST, 0);
4312 }
4313 else {
4314 /* Sub-iter - calculate on the fly */
4315 VISIT(c, expr, gen->iter);
4316 ADDOP(c, GET_ITER);
4317 }
4318 compiler_use_next_block(c, start);
4319 ADDOP_JREL(c, FOR_ITER, anchor);
4320 NEXT_BLOCK(c);
4321 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 /* XXX this needs to be cleaned up...a lot! */
4324 n = asdl_seq_LEN(gen->ifs);
4325 for (i = 0; i < n; i++) {
4326 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004327 if (!compiler_jump_if(c, e, if_cleanup, 0))
4328 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 NEXT_BLOCK(c);
4330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 if (++gen_index < asdl_seq_LEN(generators))
4333 if (!compiler_comprehension_generator(c,
4334 generators, gen_index,
4335 elt, val, type))
4336 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 /* only append after the last for generator */
4339 if (gen_index >= asdl_seq_LEN(generators)) {
4340 /* comprehension specific code */
4341 switch (type) {
4342 case COMP_GENEXP:
4343 VISIT(c, expr, elt);
4344 ADDOP(c, YIELD_VALUE);
4345 ADDOP(c, POP_TOP);
4346 break;
4347 case COMP_LISTCOMP:
4348 VISIT(c, expr, elt);
4349 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4350 break;
4351 case COMP_SETCOMP:
4352 VISIT(c, expr, elt);
4353 ADDOP_I(c, SET_ADD, gen_index + 1);
4354 break;
4355 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004356 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004359 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 ADDOP_I(c, MAP_ADD, gen_index + 1);
4361 break;
4362 default:
4363 return 0;
4364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 compiler_use_next_block(c, skip);
4367 }
4368 compiler_use_next_block(c, if_cleanup);
4369 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4370 compiler_use_next_block(c, anchor);
4371
4372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373}
4374
4375static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376compiler_async_comprehension_generator(struct compiler *c,
4377 asdl_seq *generators, int gen_index,
4378 expr_ty elt, expr_ty val, int type)
4379{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004380 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004381 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004382 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004383 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004384 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004385 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004386
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004387 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004388 return 0;
4389 }
4390
4391 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4392
4393 if (gen_index == 0) {
4394 /* Receive outermost iter as an implicit argument */
4395 c->u->u_argcount = 1;
4396 ADDOP_I(c, LOAD_FAST, 0);
4397 }
4398 else {
4399 /* Sub-iter - calculate on the fly */
4400 VISIT(c, expr, gen->iter);
4401 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004402 }
4403
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004404 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004405
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004406 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004407 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004408 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004409 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004410 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004411 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004412
4413 n = asdl_seq_LEN(gen->ifs);
4414 for (i = 0; i < n; i++) {
4415 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004416 if (!compiler_jump_if(c, e, if_cleanup, 0))
4417 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004418 NEXT_BLOCK(c);
4419 }
4420
4421 if (++gen_index < asdl_seq_LEN(generators))
4422 if (!compiler_comprehension_generator(c,
4423 generators, gen_index,
4424 elt, val, type))
4425 return 0;
4426
4427 /* only append after the last for generator */
4428 if (gen_index >= asdl_seq_LEN(generators)) {
4429 /* comprehension specific code */
4430 switch (type) {
4431 case COMP_GENEXP:
4432 VISIT(c, expr, elt);
4433 ADDOP(c, YIELD_VALUE);
4434 ADDOP(c, POP_TOP);
4435 break;
4436 case COMP_LISTCOMP:
4437 VISIT(c, expr, elt);
4438 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4439 break;
4440 case COMP_SETCOMP:
4441 VISIT(c, expr, elt);
4442 ADDOP_I(c, SET_ADD, gen_index + 1);
4443 break;
4444 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004445 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004446 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004447 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004448 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004449 ADDOP_I(c, MAP_ADD, gen_index + 1);
4450 break;
4451 default:
4452 return 0;
4453 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004454 }
4455 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004456 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4457
4458 compiler_use_next_block(c, except);
4459 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004460
4461 return 1;
4462}
4463
4464static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004465compiler_comprehension(struct compiler *c, expr_ty e, int type,
4466 identifier name, asdl_seq *generators, expr_ty elt,
4467 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004470 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004471 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004472 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004473
Miss Islington (bot)ec8a9732020-03-19 04:54:16 -07004474 if (IS_TOP_LEVEL_AWAIT(c)) {
4475 c->u->u_ste->ste_coroutine = 1;
4476 }
4477 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004478
Miss Islington (bot)ec8a9732020-03-19 04:54:16 -07004479 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004480 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4481 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004482 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 }
4485
4486 is_async_generator = c->u->u_ste->ste_coroutine;
4487
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004488 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489 compiler_error(c, "asynchronous comprehension outside of "
4490 "an asynchronous function");
4491 goto error_in_scope;
4492 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 if (type != COMP_GENEXP) {
4495 int op;
4496 switch (type) {
4497 case COMP_LISTCOMP:
4498 op = BUILD_LIST;
4499 break;
4500 case COMP_SETCOMP:
4501 op = BUILD_SET;
4502 break;
4503 case COMP_DICTCOMP:
4504 op = BUILD_MAP;
4505 break;
4506 default:
4507 PyErr_Format(PyExc_SystemError,
4508 "unknown comprehension type %d", type);
4509 goto error_in_scope;
4510 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 ADDOP_I(c, op, 0);
4513 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 if (!compiler_comprehension_generator(c, generators, 0, elt,
4516 val, type))
4517 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 if (type != COMP_GENEXP) {
4520 ADDOP(c, RETURN_VALUE);
4521 }
4522
4523 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004524 qualname = c->u->u_qualname;
4525 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004527 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 goto error;
4529
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004530 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004532 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 Py_DECREF(co);
4534
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 VISIT(c, expr, outermost->iter);
4536
4537 if (outermost->is_async) {
4538 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004539 } else {
4540 ADDOP(c, GET_ITER);
4541 }
4542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004544
4545 if (is_async_generator && type != COMP_GENEXP) {
4546 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004547 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548 ADDOP(c, YIELD_FROM);
4549 }
4550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004552error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004554error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004555 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 Py_XDECREF(co);
4557 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004558}
4559
4560static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004561compiler_genexp(struct compiler *c, expr_ty e)
4562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 static identifier name;
4564 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004565 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (!name)
4567 return 0;
4568 }
4569 assert(e->kind == GeneratorExp_kind);
4570 return compiler_comprehension(c, e, COMP_GENEXP, name,
4571 e->v.GeneratorExp.generators,
4572 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004573}
4574
4575static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004576compiler_listcomp(struct compiler *c, expr_ty e)
4577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 static identifier name;
4579 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004580 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (!name)
4582 return 0;
4583 }
4584 assert(e->kind == ListComp_kind);
4585 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4586 e->v.ListComp.generators,
4587 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004588}
4589
4590static int
4591compiler_setcomp(struct compiler *c, expr_ty e)
4592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 static identifier name;
4594 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004595 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 if (!name)
4597 return 0;
4598 }
4599 assert(e->kind == SetComp_kind);
4600 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4601 e->v.SetComp.generators,
4602 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004603}
4604
4605
4606static int
4607compiler_dictcomp(struct compiler *c, expr_ty e)
4608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 static identifier name;
4610 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004611 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (!name)
4613 return 0;
4614 }
4615 assert(e->kind == DictComp_kind);
4616 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4617 e->v.DictComp.generators,
4618 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004619}
4620
4621
4622static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004623compiler_visit_keyword(struct compiler *c, keyword_ty k)
4624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 VISIT(c, expr, k->value);
4626 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004627}
4628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004630 whether they are true or false.
4631
4632 Return values: 1 for true, 0 for false, -1 for non-constant.
4633 */
4634
4635static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004636expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004637{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004638 if (e->kind == Constant_kind) {
4639 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004640 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004641 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004642}
4643
Yury Selivanov75445082015-05-11 22:57:16 -04004644
4645/*
4646 Implements the async with statement.
4647
4648 The semantics outlined in that PEP are as follows:
4649
4650 async with EXPR as VAR:
4651 BLOCK
4652
4653 It is implemented roughly as:
4654
4655 context = EXPR
4656 exit = context.__aexit__ # not calling it
4657 value = await context.__aenter__()
4658 try:
4659 VAR = value # if VAR present in the syntax
4660 BLOCK
4661 finally:
4662 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004663 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004664 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004665 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004666 if not (await exit(*exc)):
4667 raise
4668 */
4669static int
4670compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4671{
4672 basicblock *block, *finally;
4673 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4674
4675 assert(s->kind == AsyncWith_kind);
Miss Islington (bot)f7e32fc2020-03-14 21:46:26 -07004676 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004677 c->u->u_ste->ste_coroutine = 1;
4678 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004679 return compiler_error(c, "'async with' outside async function");
4680 }
Yury Selivanov75445082015-05-11 22:57:16 -04004681
4682 block = compiler_new_block(c);
4683 finally = compiler_new_block(c);
4684 if (!block || !finally)
4685 return 0;
4686
4687 /* Evaluate EXPR */
4688 VISIT(c, expr, item->context_expr);
4689
4690 ADDOP(c, BEFORE_ASYNC_WITH);
4691 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004692 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004693 ADDOP(c, YIELD_FROM);
4694
4695 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4696
4697 /* SETUP_ASYNC_WITH pushes a finally block. */
4698 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004699 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004700 return 0;
4701 }
4702
4703 if (item->optional_vars) {
4704 VISIT(c, expr, item->optional_vars);
4705 }
4706 else {
4707 /* Discard result from context.__aenter__() */
4708 ADDOP(c, POP_TOP);
4709 }
4710
4711 pos++;
4712 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4713 /* BLOCK code */
4714 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4715 else if (!compiler_async_with(c, s, pos))
4716 return 0;
4717
4718 /* End of try block; start the finally block */
4719 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004720 ADDOP(c, BEGIN_FINALLY);
4721 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004722
Yury Selivanov75445082015-05-11 22:57:16 -04004723 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004724 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004725 return 0;
4726
4727 /* Finally block starts; context.__exit__ is on the stack under
4728 the exception or return information. Just issue our magic
4729 opcode. */
4730 ADDOP(c, WITH_CLEANUP_START);
4731
4732 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004733 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004734 ADDOP(c, YIELD_FROM);
4735
4736 ADDOP(c, WITH_CLEANUP_FINISH);
4737
4738 /* Finally block ends. */
4739 ADDOP(c, END_FINALLY);
4740 compiler_pop_fblock(c, FINALLY_END, finally);
4741 return 1;
4742}
4743
4744
Guido van Rossumc2e20742006-02-27 22:32:47 +00004745/*
4746 Implements the with statement from PEP 343.
4747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004749
4750 with EXPR as VAR:
4751 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752
Guido van Rossumc2e20742006-02-27 22:32:47 +00004753 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754
Thomas Wouters477c8d52006-05-27 19:21:47 +00004755 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004756 exit = context.__exit__ # not calling it
4757 value = context.__enter__()
4758 try:
4759 VAR = value # if VAR present in the syntax
4760 BLOCK
4761 finally:
4762 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004763 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004764 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004765 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004766 exit(*exc)
4767 */
4768static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004769compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004770{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004771 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004772 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004773
4774 assert(s->kind == With_kind);
4775
Guido van Rossumc2e20742006-02-27 22:32:47 +00004776 block = compiler_new_block(c);
4777 finally = compiler_new_block(c);
4778 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004779 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004780
Thomas Wouters477c8d52006-05-27 19:21:47 +00004781 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004782 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004783 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004784
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004785 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004786 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004787 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004788 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004789 }
4790
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004791 if (item->optional_vars) {
4792 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004793 }
4794 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004796 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004797 }
4798
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004799 pos++;
4800 if (pos == asdl_seq_LEN(s->v.With.items))
4801 /* BLOCK code */
4802 VISIT_SEQ(c, stmt, s->v.With.body)
4803 else if (!compiler_with(c, s, pos))
4804 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004805
4806 /* End of try block; start the finally block */
4807 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004808 ADDOP(c, BEGIN_FINALLY);
4809 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004810
Guido van Rossumc2e20742006-02-27 22:32:47 +00004811 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004812 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004813 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004814
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004815 /* Finally block starts; context.__exit__ is on the stack under
4816 the exception or return information. Just issue our magic
4817 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004818 ADDOP(c, WITH_CLEANUP_START);
4819 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004820
4821 /* Finally block ends. */
4822 ADDOP(c, END_FINALLY);
4823 compiler_pop_fblock(c, FINALLY_END, finally);
4824 return 1;
4825}
4826
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004827static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004828compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004831 case NamedExpr_kind:
4832 VISIT(c, expr, e->v.NamedExpr.value);
4833 ADDOP(c, DUP_TOP);
4834 VISIT(c, expr, e->v.NamedExpr.target);
4835 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 case BoolOp_kind:
4837 return compiler_boolop(c, e);
4838 case BinOp_kind:
4839 VISIT(c, expr, e->v.BinOp.left);
4840 VISIT(c, expr, e->v.BinOp.right);
4841 ADDOP(c, binop(c, e->v.BinOp.op));
4842 break;
4843 case UnaryOp_kind:
4844 VISIT(c, expr, e->v.UnaryOp.operand);
4845 ADDOP(c, unaryop(e->v.UnaryOp.op));
4846 break;
4847 case Lambda_kind:
4848 return compiler_lambda(c, e);
4849 case IfExp_kind:
4850 return compiler_ifexp(c, e);
4851 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004852 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004854 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 case GeneratorExp_kind:
4856 return compiler_genexp(c, e);
4857 case ListComp_kind:
4858 return compiler_listcomp(c, e);
4859 case SetComp_kind:
4860 return compiler_setcomp(c, e);
4861 case DictComp_kind:
4862 return compiler_dictcomp(c, e);
4863 case Yield_kind:
4864 if (c->u->u_ste->ste_type != FunctionBlock)
4865 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004866 if (e->v.Yield.value) {
4867 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 }
4869 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004870 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004872 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004874 case YieldFrom_kind:
4875 if (c->u->u_ste->ste_type != FunctionBlock)
4876 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004877
4878 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4879 return compiler_error(c, "'yield from' inside async function");
4880
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004881 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004882 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004883 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004884 ADDOP(c, YIELD_FROM);
4885 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004886 case Await_kind:
Miss Islington (bot)f7e32fc2020-03-14 21:46:26 -07004887 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004888 if (c->u->u_ste->ste_type != FunctionBlock){
4889 return compiler_error(c, "'await' outside function");
4890 }
Yury Selivanov75445082015-05-11 22:57:16 -04004891
Victor Stinner331a6a52019-05-27 16:39:22 +02004892 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004893 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4894 return compiler_error(c, "'await' outside async function");
4895 }
4896 }
Yury Selivanov75445082015-05-11 22:57:16 -04004897
4898 VISIT(c, expr, e->v.Await.value);
4899 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004900 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004901 ADDOP(c, YIELD_FROM);
4902 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 case Compare_kind:
4904 return compiler_compare(c, e);
4905 case Call_kind:
4906 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004907 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004908 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004909 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004910 case JoinedStr_kind:
4911 return compiler_joined_str(c, e);
4912 case FormattedValue_kind:
4913 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 /* The following exprs can be assignment targets. */
4915 case Attribute_kind:
4916 if (e->v.Attribute.ctx != AugStore)
4917 VISIT(c, expr, e->v.Attribute.value);
4918 switch (e->v.Attribute.ctx) {
4919 case AugLoad:
4920 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004921 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 case Load:
4923 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4924 break;
4925 case AugStore:
4926 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004927 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 case Store:
4929 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4930 break;
4931 case Del:
4932 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4933 break;
4934 case Param:
4935 default:
4936 PyErr_SetString(PyExc_SystemError,
4937 "param invalid in attribute expression");
4938 return 0;
4939 }
4940 break;
4941 case Subscript_kind:
4942 switch (e->v.Subscript.ctx) {
4943 case AugLoad:
4944 VISIT(c, expr, e->v.Subscript.value);
4945 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4946 break;
4947 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004948 if (!check_subscripter(c, e->v.Subscript.value)) {
4949 return 0;
4950 }
4951 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4952 return 0;
4953 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 VISIT(c, expr, e->v.Subscript.value);
4955 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4956 break;
4957 case AugStore:
4958 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4959 break;
4960 case Store:
4961 VISIT(c, expr, e->v.Subscript.value);
4962 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4963 break;
4964 case Del:
4965 VISIT(c, expr, e->v.Subscript.value);
4966 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4967 break;
4968 case Param:
4969 default:
4970 PyErr_SetString(PyExc_SystemError,
4971 "param invalid in subscript expression");
4972 return 0;
4973 }
4974 break;
4975 case Starred_kind:
4976 switch (e->v.Starred.ctx) {
4977 case Store:
4978 /* In all legitimate cases, the Starred node was already replaced
4979 * by compiler_list/compiler_tuple. XXX: is that okay? */
4980 return compiler_error(c,
4981 "starred assignment target must be in a list or tuple");
4982 default:
4983 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004984 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 case Name_kind:
4987 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4988 /* child nodes of List and Tuple will have expr_context set */
4989 case List_kind:
4990 return compiler_list(c, e);
4991 case Tuple_kind:
4992 return compiler_tuple(c, e);
4993 }
4994 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004995}
4996
4997static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004998compiler_visit_expr(struct compiler *c, expr_ty e)
4999{
5000 /* If expr e has a different line number than the last expr/stmt,
5001 set a new line number for the next instruction.
5002 */
5003 int old_lineno = c->u->u_lineno;
5004 int old_col_offset = c->u->u_col_offset;
5005 if (e->lineno != c->u->u_lineno) {
5006 c->u->u_lineno = e->lineno;
5007 c->u->u_lineno_set = 0;
5008 }
5009 /* Updating the column offset is always harmless. */
5010 c->u->u_col_offset = e->col_offset;
5011
5012 int res = compiler_visit_expr1(c, e);
5013
5014 if (old_lineno != c->u->u_lineno) {
5015 c->u->u_lineno = old_lineno;
5016 c->u->u_lineno_set = 0;
5017 }
5018 c->u->u_col_offset = old_col_offset;
5019 return res;
5020}
5021
5022static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005023compiler_augassign(struct compiler *c, stmt_ty s)
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 expr_ty e = s->v.AugAssign.target;
5026 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 switch (e->kind) {
5031 case Attribute_kind:
5032 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005033 AugLoad, e->lineno, e->col_offset,
5034 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 if (auge == NULL)
5036 return 0;
5037 VISIT(c, expr, auge);
5038 VISIT(c, expr, s->v.AugAssign.value);
5039 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5040 auge->v.Attribute.ctx = AugStore;
5041 VISIT(c, expr, auge);
5042 break;
5043 case Subscript_kind:
5044 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005045 AugLoad, e->lineno, e->col_offset,
5046 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 if (auge == NULL)
5048 return 0;
5049 VISIT(c, expr, auge);
5050 VISIT(c, expr, s->v.AugAssign.value);
5051 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5052 auge->v.Subscript.ctx = AugStore;
5053 VISIT(c, expr, auge);
5054 break;
5055 case Name_kind:
5056 if (!compiler_nameop(c, e->v.Name.id, Load))
5057 return 0;
5058 VISIT(c, expr, s->v.AugAssign.value);
5059 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5060 return compiler_nameop(c, e->v.Name.id, Store);
5061 default:
5062 PyErr_Format(PyExc_SystemError,
5063 "invalid node type (%d) for augmented assignment",
5064 e->kind);
5065 return 0;
5066 }
5067 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005068}
5069
5070static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005071check_ann_expr(struct compiler *c, expr_ty e)
5072{
5073 VISIT(c, expr, e);
5074 ADDOP(c, POP_TOP);
5075 return 1;
5076}
5077
5078static int
5079check_annotation(struct compiler *c, stmt_ty s)
5080{
5081 /* Annotations are only evaluated in a module or class. */
5082 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5083 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5084 return check_ann_expr(c, s->v.AnnAssign.annotation);
5085 }
5086 return 1;
5087}
5088
5089static int
5090check_ann_slice(struct compiler *c, slice_ty sl)
5091{
5092 switch(sl->kind) {
5093 case Index_kind:
5094 return check_ann_expr(c, sl->v.Index.value);
5095 case Slice_kind:
5096 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5097 return 0;
5098 }
5099 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5100 return 0;
5101 }
5102 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5103 return 0;
5104 }
5105 break;
5106 default:
5107 PyErr_SetString(PyExc_SystemError,
5108 "unexpected slice kind");
5109 return 0;
5110 }
5111 return 1;
5112}
5113
5114static int
5115check_ann_subscr(struct compiler *c, slice_ty sl)
5116{
5117 /* We check that everything in a subscript is defined at runtime. */
5118 Py_ssize_t i, n;
5119
5120 switch (sl->kind) {
5121 case Index_kind:
5122 case Slice_kind:
5123 if (!check_ann_slice(c, sl)) {
5124 return 0;
5125 }
5126 break;
5127 case ExtSlice_kind:
5128 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5129 for (i = 0; i < n; i++) {
5130 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5131 switch (subsl->kind) {
5132 case Index_kind:
5133 case Slice_kind:
5134 if (!check_ann_slice(c, subsl)) {
5135 return 0;
5136 }
5137 break;
5138 case ExtSlice_kind:
5139 default:
5140 PyErr_SetString(PyExc_SystemError,
5141 "extended slice invalid in nested slice");
5142 return 0;
5143 }
5144 }
5145 break;
5146 default:
5147 PyErr_Format(PyExc_SystemError,
5148 "invalid subscript kind %d", sl->kind);
5149 return 0;
5150 }
5151 return 1;
5152}
5153
5154static int
5155compiler_annassign(struct compiler *c, stmt_ty s)
5156{
5157 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005158 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005159
5160 assert(s->kind == AnnAssign_kind);
5161
5162 /* We perform the actual assignment first. */
5163 if (s->v.AnnAssign.value) {
5164 VISIT(c, expr, s->v.AnnAssign.value);
5165 VISIT(c, expr, targ);
5166 }
5167 switch (targ->kind) {
5168 case Name_kind:
5169 /* If we have a simple name in a module or class, store annotation. */
5170 if (s->v.AnnAssign.simple &&
5171 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5172 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005173 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5174 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5175 }
5176 else {
5177 VISIT(c, expr, s->v.AnnAssign.annotation);
5178 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005179 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005180 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005181 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005182 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005183 }
5184 break;
5185 case Attribute_kind:
5186 if (!s->v.AnnAssign.value &&
5187 !check_ann_expr(c, targ->v.Attribute.value)) {
5188 return 0;
5189 }
5190 break;
5191 case Subscript_kind:
5192 if (!s->v.AnnAssign.value &&
5193 (!check_ann_expr(c, targ->v.Subscript.value) ||
5194 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5195 return 0;
5196 }
5197 break;
5198 default:
5199 PyErr_Format(PyExc_SystemError,
5200 "invalid node type (%d) for annotated assignment",
5201 targ->kind);
5202 return 0;
5203 }
5204 /* Annotation is evaluated last. */
5205 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5206 return 0;
5207 }
5208 return 1;
5209}
5210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005211/* Raises a SyntaxError and returns 0.
5212 If something goes wrong, a different exception may be raised.
5213*/
5214
5215static int
5216compiler_error(struct compiler *c, const char *errstr)
5217{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005218 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220
Victor Stinner14e461d2013-08-26 22:28:21 +02005221 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 if (!loc) {
5223 Py_INCREF(Py_None);
5224 loc = Py_None;
5225 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005226 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005227 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 if (!u)
5229 goto exit;
5230 v = Py_BuildValue("(zO)", errstr, u);
5231 if (!v)
5232 goto exit;
5233 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005234 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 Py_DECREF(loc);
5236 Py_XDECREF(u);
5237 Py_XDECREF(v);
5238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005239}
5240
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005241/* Emits a SyntaxWarning and returns 1 on success.
5242 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5243 and returns 0.
5244*/
5245static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005246compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005247{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005248 va_list vargs;
5249#ifdef HAVE_STDARG_PROTOTYPES
5250 va_start(vargs, format);
5251#else
5252 va_start(vargs);
5253#endif
5254 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5255 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005256 if (msg == NULL) {
5257 return 0;
5258 }
5259 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5260 c->u->u_lineno, NULL, NULL) < 0)
5261 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005262 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005263 /* Replace the SyntaxWarning exception with a SyntaxError
5264 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005265 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005266 assert(PyUnicode_AsUTF8(msg) != NULL);
5267 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005268 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005269 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005270 return 0;
5271 }
5272 Py_DECREF(msg);
5273 return 1;
5274}
5275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005276static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277compiler_handle_subscr(struct compiler *c, const char *kind,
5278 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 /* XXX this code is duplicated */
5283 switch (ctx) {
5284 case AugLoad: /* fall through to Load */
5285 case Load: op = BINARY_SUBSCR; break;
5286 case AugStore:/* fall through to Store */
5287 case Store: op = STORE_SUBSCR; break;
5288 case Del: op = DELETE_SUBSCR; break;
5289 case Param:
5290 PyErr_Format(PyExc_SystemError,
5291 "invalid %s kind %d in subscript\n",
5292 kind, ctx);
5293 return 0;
5294 }
5295 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005296 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 }
5298 else if (ctx == AugStore) {
5299 ADDOP(c, ROT_THREE);
5300 }
5301 ADDOP(c, op);
5302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303}
5304
5305static int
5306compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 int n = 2;
5309 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 /* only handles the cases where BUILD_SLICE is emitted */
5312 if (s->v.Slice.lower) {
5313 VISIT(c, expr, s->v.Slice.lower);
5314 }
5315 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005316 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 if (s->v.Slice.upper) {
5320 VISIT(c, expr, s->v.Slice.upper);
5321 }
5322 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005323 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 }
5325
5326 if (s->v.Slice.step) {
5327 n++;
5328 VISIT(c, expr, s->v.Slice.step);
5329 }
5330 ADDOP_I(c, BUILD_SLICE, n);
5331 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005332}
5333
5334static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5336 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 switch (s->kind) {
5339 case Slice_kind:
5340 return compiler_slice(c, s, ctx);
5341 case Index_kind:
5342 VISIT(c, expr, s->v.Index.value);
5343 break;
5344 case ExtSlice_kind:
5345 default:
5346 PyErr_SetString(PyExc_SystemError,
5347 "extended slice invalid in nested slice");
5348 return 0;
5349 }
5350 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351}
5352
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005353static int
5354compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5355{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005356 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 switch (s->kind) {
5358 case Index_kind:
5359 kindname = "index";
5360 if (ctx != AugStore) {
5361 VISIT(c, expr, s->v.Index.value);
5362 }
5363 break;
5364 case Slice_kind:
5365 kindname = "slice";
5366 if (ctx != AugStore) {
5367 if (!compiler_slice(c, s, ctx))
5368 return 0;
5369 }
5370 break;
5371 case ExtSlice_kind:
5372 kindname = "extended slice";
5373 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005374 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 for (i = 0; i < n; i++) {
5376 slice_ty sub = (slice_ty)asdl_seq_GET(
5377 s->v.ExtSlice.dims, i);
5378 if (!compiler_visit_nested_slice(c, sub, ctx))
5379 return 0;
5380 }
5381 ADDOP_I(c, BUILD_TUPLE, n);
5382 }
5383 break;
5384 default:
5385 PyErr_Format(PyExc_SystemError,
5386 "invalid subscript kind %d", s->kind);
5387 return 0;
5388 }
5389 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005390}
5391
Thomas Wouters89f507f2006-12-13 04:49:30 +00005392/* End of the compiler section, beginning of the assembler section */
5393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394/* do depth-first search of basic block graph, starting with block.
5395 post records the block indices in post-order.
5396
5397 XXX must handle implicit jumps from one block to next
5398*/
5399
Thomas Wouters89f507f2006-12-13 04:49:30 +00005400struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 PyObject *a_bytecode; /* string containing bytecode */
5402 int a_offset; /* offset into bytecode */
5403 int a_nblocks; /* number of reachable blocks */
5404 basicblock **a_postorder; /* list of blocks in dfs postorder */
5405 PyObject *a_lnotab; /* string containing lnotab */
5406 int a_lnotab_off; /* offset into lnotab */
5407 int a_lineno; /* last lineno of emitted instruction */
5408 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005409};
5410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005411static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005412dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005413{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005414 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005415
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005416 /* Get rid of recursion for normal control flow.
5417 Since the number of blocks is limited, unused space in a_postorder
5418 (from a_nblocks to end) can be used as a stack for still not ordered
5419 blocks. */
5420 for (j = end; b && !b->b_seen; b = b->b_next) {
5421 b->b_seen = 1;
5422 assert(a->a_nblocks < j);
5423 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005425 while (j < end) {
5426 b = a->a_postorder[j++];
5427 for (i = 0; i < b->b_iused; i++) {
5428 struct instr *instr = &b->b_instr[i];
5429 if (instr->i_jrel || instr->i_jabs)
5430 dfs(c, instr->i_target, a, j);
5431 }
5432 assert(a->a_nblocks < j);
5433 a->a_postorder[a->a_nblocks++] = b;
5434 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005435}
5436
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005437Py_LOCAL_INLINE(void)
5438stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005439{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005440 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005441 if (b->b_startdepth < depth) {
5442 assert(b->b_startdepth < 0);
5443 b->b_startdepth = depth;
5444 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446}
5447
5448/* Find the flow path that needs the largest stack. We assume that
5449 * cycles in the flow graph have no net effect on the stack depth.
5450 */
5451static int
5452stackdepth(struct compiler *c)
5453{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005454 basicblock *b, *entryblock = NULL;
5455 basicblock **stack, **sp;
5456 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 b->b_startdepth = INT_MIN;
5459 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005460 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 }
5462 if (!entryblock)
5463 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005464 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5465 if (!stack) {
5466 PyErr_NoMemory();
5467 return -1;
5468 }
5469
5470 sp = stack;
5471 stackdepth_push(&sp, entryblock, 0);
5472 while (sp != stack) {
5473 b = *--sp;
5474 int depth = b->b_startdepth;
5475 assert(depth >= 0);
5476 basicblock *next = b->b_next;
5477 for (int i = 0; i < b->b_iused; i++) {
5478 struct instr *instr = &b->b_instr[i];
5479 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5480 if (effect == PY_INVALID_STACK_EFFECT) {
5481 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5482 Py_FatalError("PyCompile_OpcodeStackEffect()");
5483 }
5484 int new_depth = depth + effect;
5485 if (new_depth > maxdepth) {
5486 maxdepth = new_depth;
5487 }
5488 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5489 if (instr->i_jrel || instr->i_jabs) {
5490 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5491 assert(effect != PY_INVALID_STACK_EFFECT);
5492 int target_depth = depth + effect;
5493 if (target_depth > maxdepth) {
5494 maxdepth = target_depth;
5495 }
5496 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005497 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005498 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005499 assert(instr->i_target->b_startdepth >= target_depth);
5500 depth = new_depth;
5501 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005502 }
5503 stackdepth_push(&sp, instr->i_target, target_depth);
5504 }
5505 depth = new_depth;
5506 if (instr->i_opcode == JUMP_ABSOLUTE ||
5507 instr->i_opcode == JUMP_FORWARD ||
5508 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005509 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005510 {
5511 /* remaining code is dead */
5512 next = NULL;
5513 break;
5514 }
5515 }
5516 if (next != NULL) {
5517 stackdepth_push(&sp, next, depth);
5518 }
5519 }
5520 PyObject_Free(stack);
5521 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522}
5523
5524static int
5525assemble_init(struct assembler *a, int nblocks, int firstlineno)
5526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 memset(a, 0, sizeof(struct assembler));
5528 a->a_lineno = firstlineno;
5529 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5530 if (!a->a_bytecode)
5531 return 0;
5532 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5533 if (!a->a_lnotab)
5534 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005535 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 PyErr_NoMemory();
5537 return 0;
5538 }
5539 a->a_postorder = (basicblock **)PyObject_Malloc(
5540 sizeof(basicblock *) * nblocks);
5541 if (!a->a_postorder) {
5542 PyErr_NoMemory();
5543 return 0;
5544 }
5545 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005546}
5547
5548static void
5549assemble_free(struct assembler *a)
5550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 Py_XDECREF(a->a_bytecode);
5552 Py_XDECREF(a->a_lnotab);
5553 if (a->a_postorder)
5554 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555}
5556
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005557static int
5558blocksize(basicblock *b)
5559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 int i;
5561 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005564 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566}
5567
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005568/* Appends a pair to the end of the line number table, a_lnotab, representing
5569 the instruction's bytecode offset and line number. See
5570 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005571
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005572static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005573assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005576 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005578
Serhiy Storchakaab874002016-09-11 13:48:15 +03005579 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 if(d_bytecode == 0 && d_lineno == 0)
5585 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 if (d_bytecode > 255) {
5588 int j, nbytes, ncodes = d_bytecode / 255;
5589 nbytes = a->a_lnotab_off + 2 * ncodes;
5590 len = PyBytes_GET_SIZE(a->a_lnotab);
5591 if (nbytes >= len) {
5592 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5593 len = nbytes;
5594 else if (len <= INT_MAX / 2)
5595 len *= 2;
5596 else {
5597 PyErr_NoMemory();
5598 return 0;
5599 }
5600 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5601 return 0;
5602 }
5603 lnotab = (unsigned char *)
5604 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5605 for (j = 0; j < ncodes; j++) {
5606 *lnotab++ = 255;
5607 *lnotab++ = 0;
5608 }
5609 d_bytecode -= ncodes * 255;
5610 a->a_lnotab_off += ncodes * 2;
5611 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005612 assert(0 <= d_bytecode && d_bytecode <= 255);
5613
5614 if (d_lineno < -128 || 127 < d_lineno) {
5615 int j, nbytes, ncodes, k;
5616 if (d_lineno < 0) {
5617 k = -128;
5618 /* use division on positive numbers */
5619 ncodes = (-d_lineno) / 128;
5620 }
5621 else {
5622 k = 127;
5623 ncodes = d_lineno / 127;
5624 }
5625 d_lineno -= ncodes * k;
5626 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 nbytes = a->a_lnotab_off + 2 * ncodes;
5628 len = PyBytes_GET_SIZE(a->a_lnotab);
5629 if (nbytes >= len) {
5630 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5631 len = nbytes;
5632 else if (len <= INT_MAX / 2)
5633 len *= 2;
5634 else {
5635 PyErr_NoMemory();
5636 return 0;
5637 }
5638 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5639 return 0;
5640 }
5641 lnotab = (unsigned char *)
5642 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5643 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005644 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 d_bytecode = 0;
5646 for (j = 1; j < ncodes; j++) {
5647 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005648 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 a->a_lnotab_off += ncodes * 2;
5651 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005652 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 len = PyBytes_GET_SIZE(a->a_lnotab);
5655 if (a->a_lnotab_off + 2 >= len) {
5656 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5657 return 0;
5658 }
5659 lnotab = (unsigned char *)
5660 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 a->a_lnotab_off += 2;
5663 if (d_bytecode) {
5664 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005665 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 }
5667 else { /* First line of a block; def stmt, etc. */
5668 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005669 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 }
5671 a->a_lineno = i->i_lineno;
5672 a->a_lineno_off = a->a_offset;
5673 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005674}
5675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676/* assemble_emit()
5677 Extend the bytecode with a new instruction.
5678 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005679*/
5680
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005681static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005682assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005683{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005684 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005686 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005687
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005688 arg = i->i_oparg;
5689 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 if (i->i_lineno && !assemble_lnotab(a, i))
5691 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005692 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 if (len > PY_SSIZE_T_MAX / 2)
5694 return 0;
5695 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5696 return 0;
5697 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005698 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005700 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005702}
5703
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005704static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005705assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005708 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 /* Compute the size of each block and fixup jump args.
5712 Replace block pointer with position in bytecode. */
5713 do {
5714 totsize = 0;
5715 for (i = a->a_nblocks - 1; i >= 0; i--) {
5716 b = a->a_postorder[i];
5717 bsize = blocksize(b);
5718 b->b_offset = totsize;
5719 totsize += bsize;
5720 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005721 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5723 bsize = b->b_offset;
5724 for (i = 0; i < b->b_iused; i++) {
5725 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005726 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 /* Relative jumps are computed relative to
5728 the instruction pointer after fetching
5729 the jump instruction.
5730 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005731 bsize += isize;
5732 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005734 if (instr->i_jrel) {
5735 instr->i_oparg -= bsize;
5736 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005737 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005738 if (instrsize(instr->i_oparg) != isize) {
5739 extended_arg_recompile = 1;
5740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 }
5743 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 /* XXX: This is an awful hack that could hurt performance, but
5746 on the bright side it should work until we come up
5747 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 The issue is that in the first loop blocksize() is called
5750 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005751 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 So we loop until we stop seeing new EXTENDED_ARGs.
5755 The only EXTENDED_ARGs that could be popping up are
5756 ones in jump instructions. So this should converge
5757 fairly quickly.
5758 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005759 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005760}
5761
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005762static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005763dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005766 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 tuple = PyTuple_New(size);
5769 if (tuple == NULL)
5770 return NULL;
5771 while (PyDict_Next(dict, &pos, &k, &v)) {
5772 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005773 Py_INCREF(k);
5774 assert((i - offset) < size);
5775 assert((i - offset) >= 0);
5776 PyTuple_SET_ITEM(tuple, i - offset, k);
5777 }
5778 return tuple;
5779}
5780
5781static PyObject *
5782consts_dict_keys_inorder(PyObject *dict)
5783{
5784 PyObject *consts, *k, *v;
5785 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5786
5787 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5788 if (consts == NULL)
5789 return NULL;
5790 while (PyDict_Next(dict, &pos, &k, &v)) {
5791 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005792 /* The keys of the dictionary can be tuples wrapping a contant.
5793 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5794 * the object we want is always second. */
5795 if (PyTuple_CheckExact(k)) {
5796 k = PyTuple_GET_ITEM(k, 1);
5797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005799 assert(i < size);
5800 assert(i >= 0);
5801 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005803 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005804}
5805
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005806static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005807compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005810 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005812 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 if (ste->ste_nested)
5814 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005815 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005817 if (!ste->ste_generator && ste->ste_coroutine)
5818 flags |= CO_COROUTINE;
5819 if (ste->ste_generator && ste->ste_coroutine)
5820 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 if (ste->ste_varargs)
5822 flags |= CO_VARARGS;
5823 if (ste->ste_varkeywords)
5824 flags |= CO_VARKEYWORDS;
5825 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 /* (Only) inherit compilerflags in PyCF_MASK */
5828 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005829
Miss Islington (bot)f7e32fc2020-03-14 21:46:26 -07005830 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005831 ste->ste_coroutine &&
5832 !ste->ste_generator) {
5833 flags |= CO_COROUTINE;
5834 }
5835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005837}
5838
INADA Naokic2e16072018-11-26 21:23:22 +09005839// Merge *tuple* with constant cache.
5840// Unlike merge_consts_recursive(), this function doesn't work recursively.
5841static int
5842merge_const_tuple(struct compiler *c, PyObject **tuple)
5843{
5844 assert(PyTuple_CheckExact(*tuple));
5845
5846 PyObject *key = _PyCode_ConstantKey(*tuple);
5847 if (key == NULL) {
5848 return 0;
5849 }
5850
5851 // t is borrowed reference
5852 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5853 Py_DECREF(key);
5854 if (t == NULL) {
5855 return 0;
5856 }
5857 if (t == key) { // tuple is new constant.
5858 return 1;
5859 }
5860
5861 PyObject *u = PyTuple_GET_ITEM(t, 1);
5862 Py_INCREF(u);
5863 Py_DECREF(*tuple);
5864 *tuple = u;
5865 return 1;
5866}
5867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005868static PyCodeObject *
5869makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 PyObject *tmp;
5872 PyCodeObject *co = NULL;
5873 PyObject *consts = NULL;
5874 PyObject *names = NULL;
5875 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 PyObject *name = NULL;
5877 PyObject *freevars = NULL;
5878 PyObject *cellvars = NULL;
5879 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005880 Py_ssize_t nlocals;
5881 int nlocals_int;
5882 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005883 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005884
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005885 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 names = dict_keys_inorder(c->u->u_names, 0);
5887 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5888 if (!consts || !names || !varnames)
5889 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5892 if (!cellvars)
5893 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005894 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 if (!freevars)
5896 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005897
INADA Naokic2e16072018-11-26 21:23:22 +09005898 if (!merge_const_tuple(c, &names) ||
5899 !merge_const_tuple(c, &varnames) ||
5900 !merge_const_tuple(c, &cellvars) ||
5901 !merge_const_tuple(c, &freevars))
5902 {
5903 goto error;
5904 }
5905
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005906 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005907 assert(nlocals < INT_MAX);
5908 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 flags = compute_code_flags(c);
5911 if (flags < 0)
5912 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5915 if (!bytecode)
5916 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005918 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5919 if (!tmp)
5920 goto error;
5921 Py_DECREF(consts);
5922 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005923 if (!merge_const_tuple(c, &consts)) {
5924 goto error;
5925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005927 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005928 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005929 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005930 maxdepth = stackdepth(c);
5931 if (maxdepth < 0) {
5932 goto error;
5933 }
Miss Islington (bot)cb083f72019-07-01 04:29:14 -07005934 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5935 posonlyargcount, kwonlyargcount, nlocals_int,
5936 maxdepth, flags, bytecode, consts, names,
5937 varnames, freevars, cellvars, c->c_filename,
5938 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005939 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 Py_XDECREF(consts);
5941 Py_XDECREF(names);
5942 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 Py_XDECREF(name);
5944 Py_XDECREF(freevars);
5945 Py_XDECREF(cellvars);
5946 Py_XDECREF(bytecode);
5947 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005948}
5949
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005950
5951/* For debugging purposes only */
5952#if 0
5953static void
5954dump_instr(const struct instr *i)
5955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 const char *jrel = i->i_jrel ? "jrel " : "";
5957 const char *jabs = i->i_jabs ? "jabs " : "";
5958 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005961 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005963 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005964 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5965 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005966}
5967
5968static void
5969dump_basicblock(const basicblock *b)
5970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 const char *seen = b->b_seen ? "seen " : "";
5972 const char *b_return = b->b_return ? "return " : "";
5973 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5974 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5975 if (b->b_instr) {
5976 int i;
5977 for (i = 0; i < b->b_iused; i++) {
5978 fprintf(stderr, " [%02d] ", i);
5979 dump_instr(b->b_instr + i);
5980 }
5981 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005982}
5983#endif
5984
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005985static PyCodeObject *
5986assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005988 basicblock *b, *entryblock;
5989 struct assembler a;
5990 int i, j, nblocks;
5991 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 /* Make sure every block that falls off the end returns None.
5994 XXX NEXT_BLOCK() isn't quite right, because if the last
5995 block ends with a jump or return b_next shouldn't set.
5996 */
5997 if (!c->u->u_curblock->b_return) {
5998 NEXT_BLOCK(c);
5999 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006000 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 ADDOP(c, RETURN_VALUE);
6002 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 nblocks = 0;
6005 entryblock = NULL;
6006 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6007 nblocks++;
6008 entryblock = b;
6009 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 /* Set firstlineno if it wasn't explicitly set. */
6012 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006013 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6015 else
6016 c->u->u_firstlineno = 1;
6017 }
6018 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6019 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006020 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 /* Can't modify the bytecode after computing jump offsets. */
6023 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 /* Emit code in reverse postorder from dfs. */
6026 for (i = a.a_nblocks - 1; i >= 0; i--) {
6027 b = a.a_postorder[i];
6028 for (j = 0; j < b->b_iused; j++)
6029 if (!assemble_emit(&a, &b->b_instr[j]))
6030 goto error;
6031 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006033 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6034 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006035 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006036 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006038 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006039 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 assemble_free(&a);
6041 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006042}
Georg Brandl8334fd92010-12-04 10:26:46 +00006043
6044#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006045PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006046PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6047 PyArena *arena)
6048{
6049 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6050}