blob: edd8625cba91ccf9bcb97361b240b2da9389d6d8 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Victor Stinnerc96be812019-05-14 17:34:56 +020027#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Serhiy Storchakaef61c522019-08-24 13:11:52 +030084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_TRY2, FINALLY_END,
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020085 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
Antoine Pitrou86a36b52011-11-25 18:56:07 +010094enum {
95 COMPILER_SCOPE_MODULE,
96 COMPILER_SCOPE_CLASS,
97 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040098 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040099 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100 COMPILER_SCOPE_COMPREHENSION,
101};
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103/* The following items change on entry and exit of code blocks.
104 They must be saved and restored when returning to a block.
105*/
106struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400110 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100111 int u_scope_type;
112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 /* The following fields are dicts that map objects to
114 the index of them in co_XXX. The index is used as
115 the argument for opcodes that refer to those collections.
116 */
117 PyObject *u_consts; /* all constants */
118 PyObject *u_names; /* all names */
119 PyObject *u_varnames; /* local variables */
120 PyObject *u_cellvars; /* cell variables */
121 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Victor Stinnerf8e32212013-11-19 23:56:34 +0100125 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100126 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 /* Pointer to the most recently allocated block. By following b_list
129 members, you can reach all early allocated blocks. */
130 basicblock *u_blocks;
131 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int u_nfblocks;
134 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_firstlineno; /* the first lineno of the block */
137 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000138 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_lineno_set; /* boolean to indicate whether instr
140 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141};
142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000148
149Note that we don't track recursion levels during compilation - the
150task of detecting and rejecting excessive levels of nesting is
151handled by the symbol analysis pass.
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153*/
154
155struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200156 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 struct symtable *c_st;
158 PyFutureFeatures *c_future; /* pointer to module's __future__ */
159 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Georg Brandl8334fd92010-12-04 10:26:46 +0000161 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 int c_interactive; /* true if in interactive mode */
163 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100164 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
165 if this value is different from zero.
166 This can be used to temporarily visit
167 nodes without emitting bytecode to
168 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
INADA Naokic2e16072018-11-26 21:23:22 +0900170 PyObject *c_const_cache; /* Python dict holding all constants,
171 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 struct compiler_unit *u; /* compiler state for current block */
173 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
174 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175};
176
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100177static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static void compiler_free(struct compiler *);
179static basicblock *compiler_new_block(struct compiler *);
180static int compiler_next_instr(struct compiler *, basicblock *);
181static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100182static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200185static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
187
188static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
189static int compiler_visit_stmt(struct compiler *, stmt_ty);
190static int compiler_visit_keyword(struct compiler *, keyword_ty);
191static int compiler_visit_expr(struct compiler *, expr_ty);
192static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700193static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200198static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500200static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400201static int compiler_async_with(struct compiler *, stmt_ty, int);
202static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100203static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400205 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500206static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400207static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000208
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700209static int compiler_sync_comprehension_generator(
210 struct compiler *c,
211 asdl_seq *generators, int gen_index,
212 expr_ty elt, expr_ty val, int type);
213
214static int compiler_async_comprehension_generator(
215 struct compiler *c,
216 asdl_seq *generators, int gen_index,
217 expr_ty elt, expr_ty val, int type);
218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000220static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400222#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000225_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Name mangling: __private becomes _classname__private.
228 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyObject *result;
230 size_t nlen, plen, ipriv;
231 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 PyUnicode_READ_CHAR(ident, 0) != '_' ||
234 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_INCREF(ident);
236 return ident;
237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 nlen = PyUnicode_GET_LENGTH(ident);
239 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 The only time a name with a dot can occur is when
243 we are compiling an import statement that has a
244 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 TODO(jhylton): Decide whether we want to support
247 mangling of the module name, e.g. __M.X.
248 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
250 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
251 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(ident);
253 return ident; /* Don't mangle __whatever__ */
254 }
255 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 ipriv = 0;
257 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
258 ipriv++;
259 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 Py_INCREF(ident);
261 return ident; /* Don't mangle if class is just underscores */
262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000264
Antoine Pitrou55bff892013-04-06 21:21:04 +0200265 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
266 PyErr_SetString(PyExc_OverflowError,
267 "private identifier too large to be mangled");
268 return NULL;
269 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
272 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
273 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
274
275 result = PyUnicode_New(1 + nlen + plen, maxchar);
276 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200278 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
279 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200280 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
284 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
285 Py_DECREF(result);
286 return NULL;
287 }
Victor Stinner8f825062012-04-27 13:55:39 +0200288 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200289 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000290}
291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292static int
293compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296
INADA Naokic2e16072018-11-26 21:23:22 +0900297 c->c_const_cache = PyDict_New();
298 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900300 }
301
302 c->c_stack = PyList_New(0);
303 if (!c->c_stack) {
304 Py_CLEAR(c->c_const_cache);
305 return 0;
306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309}
310
311PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200312PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
313 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 struct compiler c;
316 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200317 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200319 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (!__doc__) {
322 __doc__ = PyUnicode_InternFromString("__doc__");
323 if (!__doc__)
324 return NULL;
325 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000326 if (!__annotations__) {
327 __annotations__ = PyUnicode_InternFromString("__annotations__");
328 if (!__annotations__)
329 return NULL;
330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (!compiler_init(&c))
332 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200333 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 c.c_filename = filename;
335 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (c.c_future == NULL)
338 goto finally;
339 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 flags = &local_flags;
341 }
342 merged = c.c_future->ff_features | flags->cf_flags;
343 c.c_future->ff_features = merged;
344 flags->cf_flags = merged;
345 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200346 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100348 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200350 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900351 goto finally;
352 }
353
Victor Stinner14e461d2013-08-26 22:28:21 +0200354 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (c.c_st == NULL) {
356 if (!PyErr_Occurred())
357 PyErr_SetString(PyExc_SystemError, "no symtable");
358 goto finally;
359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Thomas Wouters1175c432006-02-27 22:49:54 +0000363 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 compiler_free(&c);
365 assert(co || PyErr_Occurred());
366 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367}
368
369PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200370PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
371 int optimize, PyArena *arena)
372{
373 PyObject *filename;
374 PyCodeObject *co;
375 filename = PyUnicode_DecodeFSDefault(filename_str);
376 if (filename == NULL)
377 return NULL;
378 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
379 Py_DECREF(filename);
380 return co;
381
382}
383
384PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385PyNode_Compile(struct _node *n, const char *filename)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 PyCodeObject *co = NULL;
388 mod_ty mod;
389 PyArena *arena = PyArena_New();
390 if (!arena)
391 return NULL;
392 mod = PyAST_FromNode(n, NULL, filename, arena);
393 if (mod)
394 co = PyAST_Compile(mod, filename, NULL, arena);
395 PyArena_Free(arena);
396 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000397}
398
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000399static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (c->c_st)
403 PySymtable_Free(c->c_st);
404 if (c->c_future)
405 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200406 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900407 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000409}
410
Guido van Rossum79f25d91997-04-29 20:08:16 +0000411static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_ssize_t i, n;
415 PyObject *v, *k;
416 PyObject *dict = PyDict_New();
417 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 n = PyList_Size(list);
420 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100421 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (!v) {
423 Py_DECREF(dict);
424 return NULL;
425 }
426 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300427 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_DECREF(v);
429 Py_DECREF(dict);
430 return NULL;
431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_DECREF(v);
433 }
434 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435}
436
437/* Return new dict containing names from src that match scope(s).
438
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000439src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000441values are integers, starting at offset and increasing by one for
442each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443*/
444
445static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100446dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700448 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500450 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 assert(offset >= 0);
453 if (dest == NULL)
454 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455
Meador Inge2ca63152012-07-18 14:20:11 -0500456 /* Sort the keys so that we have a deterministic order on the indexes
457 saved in the returned dictionary. These indexes are used as indexes
458 into the free and cell var storage. Therefore if they aren't
459 deterministic, then the generated bytecode is not deterministic.
460 */
461 sorted_keys = PyDict_Keys(src);
462 if (sorted_keys == NULL)
463 return NULL;
464 if (PyList_Sort(sorted_keys) != 0) {
465 Py_DECREF(sorted_keys);
466 return NULL;
467 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500468 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500469
470 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* XXX this should probably be a macro in symtable.h */
472 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500473 k = PyList_GET_ITEM(sorted_keys, key_i);
474 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(PyLong_Check(v));
476 vi = PyLong_AS_LONG(v);
477 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500482 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_DECREF(dest);
484 return NULL;
485 }
486 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300487 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_DECREF(item);
490 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return NULL;
492 }
493 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 }
Meador Inge2ca63152012-07-18 14:20:11 -0500496 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000498}
499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500static void
501compiler_unit_check(struct compiler_unit *u)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 basicblock *block;
504 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700505 assert((uintptr_t)block != 0xcbcbcbcbU);
506 assert((uintptr_t)block != 0xfbfbfbfbU);
507 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (block->b_instr != NULL) {
509 assert(block->b_ialloc > 0);
510 assert(block->b_iused > 0);
511 assert(block->b_ialloc >= block->b_iused);
512 }
513 else {
514 assert (block->b_iused == 0);
515 assert (block->b_ialloc == 0);
516 }
517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static void
521compiler_unit_free(struct compiler_unit *u)
522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 compiler_unit_check(u);
526 b = u->u_blocks;
527 while (b != NULL) {
528 if (b->b_instr)
529 PyObject_Free((void *)b->b_instr);
530 next = b->b_list;
531 PyObject_Free((void *)b);
532 b = next;
533 }
534 Py_CLEAR(u->u_ste);
535 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400536 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_CLEAR(u->u_consts);
538 Py_CLEAR(u->u_names);
539 Py_CLEAR(u->u_varnames);
540 Py_CLEAR(u->u_freevars);
541 Py_CLEAR(u->u_cellvars);
542 Py_CLEAR(u->u_private);
543 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544}
545
546static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100547compiler_enter_scope(struct compiler *c, identifier name,
548 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100551 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
554 struct compiler_unit));
555 if (!u) {
556 PyErr_NoMemory();
557 return 0;
558 }
559 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100560 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100562 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 u->u_kwonlyargcount = 0;
564 u->u_ste = PySymtable_Lookup(c->c_st, key);
565 if (!u->u_ste) {
566 compiler_unit_free(u);
567 return 0;
568 }
569 Py_INCREF(name);
570 u->u_name = name;
571 u->u_varnames = list2dict(u->u_ste->ste_varnames);
572 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
573 if (!u->u_varnames || !u->u_cellvars) {
574 compiler_unit_free(u);
575 return 0;
576 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500577 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000578 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 int res;
582 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200583 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 name = _PyUnicode_FromId(&PyId___class__);
585 if (!name) {
586 compiler_unit_free(u);
587 return 0;
588 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300589 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 if (res < 0) {
591 compiler_unit_free(u);
592 return 0;
593 }
594 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200597 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (!u->u_freevars) {
599 compiler_unit_free(u);
600 return 0;
601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 u->u_blocks = NULL;
604 u->u_nfblocks = 0;
605 u->u_firstlineno = lineno;
606 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000607 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 u->u_lineno_set = 0;
609 u->u_consts = PyDict_New();
610 if (!u->u_consts) {
611 compiler_unit_free(u);
612 return 0;
613 }
614 u->u_names = PyDict_New();
615 if (!u->u_names) {
616 compiler_unit_free(u);
617 return 0;
618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Push the old compiler_unit on the stack. */
623 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400624 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
626 Py_XDECREF(capsule);
627 compiler_unit_free(u);
628 return 0;
629 }
630 Py_DECREF(capsule);
631 u->u_private = c->u->u_private;
632 Py_XINCREF(u->u_private);
633 }
634 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100637
638 block = compiler_new_block(c);
639 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100641 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400643 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
644 if (!compiler_set_qualname(c))
645 return 0;
646 }
647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000651static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652compiler_exit_scope(struct compiler *c)
653{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100654 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel--;
658 compiler_unit_free(c->u);
659 /* Restore c->u to the parent unit. */
660 n = PyList_GET_SIZE(c->c_stack) - 1;
661 if (n >= 0) {
662 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400663 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 assert(c->u);
665 /* we are deleting from a list so this really shouldn't fail */
666 if (PySequence_DelItem(c->c_stack, n) < 0)
667 Py_FatalError("compiler_exit_scope()");
668 compiler_unit_check(c->u);
669 }
670 else
671 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673}
674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675static int
676compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100678 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 _Py_static_string(dot_locals, ".<locals>");
680 Py_ssize_t stack_size;
681 struct compiler_unit *u = c->u;
682 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100685 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400686 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 if (stack_size > 1) {
688 int scope, force_global = 0;
689 struct compiler_unit *parent;
690 PyObject *mangled, *capsule;
691
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400692 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400693 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 assert(parent);
695
Yury Selivanov75445082015-05-11 22:57:16 -0400696 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
697 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
698 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 assert(u->u_name);
700 mangled = _Py_Mangle(parent->u_private, u->u_name);
701 if (!mangled)
702 return 0;
703 scope = PyST_GetScope(parent->u_ste, mangled);
704 Py_DECREF(mangled);
705 assert(scope != GLOBAL_IMPLICIT);
706 if (scope == GLOBAL_EXPLICIT)
707 force_global = 1;
708 }
709
710 if (!force_global) {
711 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400712 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400713 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
714 dot_locals_str = _PyUnicode_FromId(&dot_locals);
715 if (dot_locals_str == NULL)
716 return 0;
717 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
718 if (base == NULL)
719 return 0;
720 }
721 else {
722 Py_INCREF(parent->u_qualname);
723 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400724 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100725 }
726 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400728 if (base != NULL) {
729 dot_str = _PyUnicode_FromId(&dot);
730 if (dot_str == NULL) {
731 Py_DECREF(base);
732 return 0;
733 }
734 name = PyUnicode_Concat(base, dot_str);
735 Py_DECREF(base);
736 if (name == NULL)
737 return 0;
738 PyUnicode_Append(&name, u->u_name);
739 if (name == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(u->u_name);
744 name = u->u_name;
745 }
746 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100747
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400748 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100749}
750
Eric V. Smith235a6f02015-09-19 14:51:32 -0400751
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752/* Allocate a new block and return a pointer to it.
753 Returns NULL on error.
754*/
755
756static basicblock *
757compiler_new_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *b;
760 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 u = c->u;
763 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
764 if (b == NULL) {
765 PyErr_NoMemory();
766 return NULL;
767 }
768 memset((void *)b, 0, sizeof(basicblock));
769 /* Extend the singly linked list of blocks with new block. */
770 b->b_list = u->u_blocks;
771 u->u_blocks = b;
772 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773}
774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776compiler_next_block(struct compiler *c)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 basicblock *block = compiler_new_block(c);
779 if (block == NULL)
780 return NULL;
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786static basicblock *
787compiler_use_next_block(struct compiler *c, basicblock *block)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(block != NULL);
790 c->u->u_curblock->b_next = block;
791 c->u->u_curblock = block;
792 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
795/* Returns the offset of the next instruction in the current block's
796 b_instr array. Resizes the b_instr as necessary.
797 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000798*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799
800static int
801compiler_next_instr(struct compiler *c, basicblock *b)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 assert(b != NULL);
804 if (b->b_instr == NULL) {
805 b->b_instr = (struct instr *)PyObject_Malloc(
806 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
807 if (b->b_instr == NULL) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc = DEFAULT_BLOCK_SIZE;
812 memset((char *)b->b_instr, 0,
813 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
814 }
815 else if (b->b_iused == b->b_ialloc) {
816 struct instr *tmp;
817 size_t oldsize, newsize;
818 oldsize = b->b_ialloc * sizeof(struct instr);
819 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000820
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700821 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyErr_NoMemory();
823 return -1;
824 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (newsize == 0) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 b->b_ialloc <<= 1;
831 tmp = (struct instr *)PyObject_Realloc(
832 (void *)b->b_instr, newsize);
833 if (tmp == NULL) {
834 PyErr_NoMemory();
835 return -1;
836 }
837 b->b_instr = tmp;
838 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
839 }
840 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841}
842
Christian Heimes2202f872008-02-06 14:31:34 +0000843/* Set the i_lineno member of the instruction at offset off if the
844 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 already been set. If it has been set, the call has no effect.
846
Christian Heimes2202f872008-02-06 14:31:34 +0000847 The line number is reset in the following cases:
848 - when entering a new scope
849 - on each statement
850 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200851 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000852 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000853*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855static void
856compiler_set_lineno(struct compiler *c, int off)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 basicblock *b;
859 if (c->u->u_lineno_set)
860 return;
861 c->u->u_lineno_set = 1;
862 b = c->u->u_curblock;
863 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864}
865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866/* Return the stack effect of opcode with argument oparg.
867
868 Some opcodes have different stack effect when jump to the target and
869 when not jump. The 'jump' parameter specifies the case:
870
871 * 0 -- when not jump
872 * 1 -- when jump
873 * -1 -- maximal
874 */
875/* XXX Make the stack effect of WITH_CLEANUP_START and
876 WITH_CLEANUP_FINISH deterministic. */
877static int
878stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300881 case NOP:
882 case EXTENDED_ARG:
883 return 0;
884
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200885 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case POP_TOP:
887 return -1;
888 case ROT_TWO:
889 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200890 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return 0;
892 case DUP_TOP:
893 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000894 case DUP_TOP_TWO:
895 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200897 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case UNARY_POSITIVE:
899 case UNARY_NEGATIVE:
900 case UNARY_NOT:
901 case UNARY_INVERT:
902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case SET_ADD:
905 case LIST_APPEND:
906 return -1;
907 case MAP_ADD:
908 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000909
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200910 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_POWER:
912 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400913 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_MODULO:
915 case BINARY_ADD:
916 case BINARY_SUBTRACT:
917 case BINARY_SUBSCR:
918 case BINARY_FLOOR_DIVIDE:
919 case BINARY_TRUE_DIVIDE:
920 return -1;
921 case INPLACE_FLOOR_DIVIDE:
922 case INPLACE_TRUE_DIVIDE:
923 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_ADD:
926 case INPLACE_SUBTRACT:
927 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400928 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case INPLACE_MODULO:
930 return -1;
931 case STORE_SUBSCR:
932 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case DELETE_SUBSCR:
934 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case BINARY_LSHIFT:
937 case BINARY_RSHIFT:
938 case BINARY_AND:
939 case BINARY_XOR:
940 case BINARY_OR:
941 return -1;
942 case INPLACE_POWER:
943 return -1;
944 case GET_ITER:
945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case PRINT_EXPR:
948 return -1;
949 case LOAD_BUILD_CLASS:
950 return 1;
951 case INPLACE_LSHIFT:
952 case INPLACE_RSHIFT:
953 case INPLACE_AND:
954 case INPLACE_XOR:
955 case INPLACE_OR:
956 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 /* 1 in the normal flow.
960 * Restore the stack position and push 6 values before jumping to
961 * the handler if an exception be raised. */
962 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400963 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400965 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* Pop a variable number of values pushed by WITH_CLEANUP_START
967 * + __exit__ or __aexit__. */
968 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case RETURN_VALUE:
970 return -1;
971 case IMPORT_STAR:
972 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700973 case SETUP_ANNOTATIONS:
974 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case YIELD_VALUE:
976 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500977 case YIELD_FROM:
978 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case POP_BLOCK:
980 return 0;
981 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200982 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200984 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200985 /* Pop 6 values when an exception was raised. */
986 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case STORE_NAME:
989 return -1;
990 case DELETE_NAME:
991 return 0;
992 case UNPACK_SEQUENCE:
993 return oparg-1;
994 case UNPACK_EX:
995 return (oparg&0xFF) + (oparg>>8);
996 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200997 /* -1 at end of iterator, 1 if continue iterating. */
998 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case STORE_ATTR:
1001 return -2;
1002 case DELETE_ATTR:
1003 return -1;
1004 case STORE_GLOBAL:
1005 return -1;
1006 case DELETE_GLOBAL:
1007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_CONST:
1009 return 1;
1010 case LOAD_NAME:
1011 return 1;
1012 case BUILD_TUPLE:
1013 case BUILD_LIST:
1014 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001015 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001017 case BUILD_LIST_UNPACK:
1018 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001019 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001020 case BUILD_SET_UNPACK:
1021 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001022 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001023 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001025 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001026 case BUILD_CONST_KEY_MAP:
1027 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_ATTR:
1029 return 0;
1030 case COMPARE_OP:
1031 return -1;
1032 case IMPORT_NAME:
1033 return -1;
1034 case IMPORT_FROM:
1035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case JUMP_ABSOLUTE:
1040 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001042 case JUMP_IF_TRUE_OR_POP:
1043 case JUMP_IF_FALSE_OR_POP:
1044 return jump ? 0 : -1;
1045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case POP_JUMP_IF_FALSE:
1047 case POP_JUMP_IF_TRUE:
1048 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case LOAD_GLOBAL:
1051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001053 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001055 /* 0 in the normal flow.
1056 * Restore the stack position and push 6 values before jumping to
1057 * the handler if an exception be raised. */
1058 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001059 case BEGIN_FINALLY:
1060 /* Actually pushes 1 value, but count 6 for balancing with
1061 * END_FINALLY and POP_FINALLY.
1062 * This is the main reason of using this opcode instead of
1063 * "LOAD_CONST None". */
1064 return 6;
1065 case CALL_FINALLY:
1066 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case LOAD_FAST:
1069 return 1;
1070 case STORE_FAST:
1071 return -1;
1072 case DELETE_FAST:
1073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case RAISE_VARARGS:
1076 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001077
1078 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001080 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001081 case CALL_METHOD:
1082 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001084 return -oparg-1;
1085 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001086 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001087 case MAKE_FUNCTION:
1088 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1089 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 case BUILD_SLICE:
1091 if (oparg == 3)
1092 return -2;
1093 else
1094 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case LOAD_CLOSURE:
1098 return 1;
1099 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001100 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return 1;
1102 case STORE_DEREF:
1103 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001104 case DELETE_DEREF:
1105 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001106
1107 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case GET_AWAITABLE:
1109 return 0;
1110 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001111 /* 0 in the normal flow.
1112 * Restore the stack position to the position before the result
1113 * of __aenter__ and push 6 values before jumping to the handler
1114 * if an exception be raised. */
1115 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case BEFORE_ASYNC_WITH:
1117 return 1;
1118 case GET_AITER:
1119 return 0;
1120 case GET_ANEXT:
1121 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001122 case GET_YIELD_FROM_ITER:
1123 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001124 case END_ASYNC_FOR:
1125 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001126 case FORMAT_VALUE:
1127 /* If there's a fmt_spec on the stack, we go from 2->1,
1128 else 1->1. */
1129 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001130 case LOAD_METHOD:
1131 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001132 case LOAD_ASSERTION_ERROR:
1133 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001135 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Larry Hastings3a907972013-11-23 14:49:22 -08001137 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138}
1139
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001140int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001141PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1142{
1143 return stack_effect(opcode, oparg, jump);
1144}
1145
1146int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001147PyCompile_OpcodeStackEffect(int opcode, int oparg)
1148{
1149 return stack_effect(opcode, oparg, -1);
1150}
1151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152/* Add an opcode with no argument.
1153 Returns 0 on failure, 1 on success.
1154*/
1155
1156static int
1157compiler_addop(struct compiler *c, int opcode)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 basicblock *b;
1160 struct instr *i;
1161 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001162 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001163 if (c->c_do_not_emit_bytecode) {
1164 return 1;
1165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 off = compiler_next_instr(c, c->u->u_curblock);
1167 if (off < 0)
1168 return 0;
1169 b = c->u->u_curblock;
1170 i = &b->b_instr[off];
1171 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001172 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (opcode == RETURN_VALUE)
1174 b->b_return = 1;
1175 compiler_set_lineno(c, off);
1176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177}
1178
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1181{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001185 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001187 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001189 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001190 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 return -1;
1194 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001195 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_DECREF(v);
1197 return -1;
1198 }
1199 Py_DECREF(v);
1200 }
1201 else
1202 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 return arg;
1204}
1205
INADA Naokic2e16072018-11-26 21:23:22 +09001206// Merge const *o* recursively and return constant key object.
1207static PyObject*
1208merge_consts_recursive(struct compiler *c, PyObject *o)
1209{
1210 // None and Ellipsis are singleton, and key is the singleton.
1211 // No need to merge object and key.
1212 if (o == Py_None || o == Py_Ellipsis) {
1213 Py_INCREF(o);
1214 return o;
1215 }
1216
1217 PyObject *key = _PyCode_ConstantKey(o);
1218 if (key == NULL) {
1219 return NULL;
1220 }
1221
1222 // t is borrowed reference
1223 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1224 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001226 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001227 Py_DECREF(key);
1228 return t;
1229 }
1230
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001232 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001234 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001235 Py_ssize_t len = PyTuple_GET_SIZE(o);
1236 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001237 PyObject *item = PyTuple_GET_ITEM(o, i);
1238 PyObject *u = merge_consts_recursive(c, item);
1239 if (u == NULL) {
1240 Py_DECREF(key);
1241 return NULL;
1242 }
1243
1244 // See _PyCode_ConstantKey()
1245 PyObject *v; // borrowed
1246 if (PyTuple_CheckExact(u)) {
1247 v = PyTuple_GET_ITEM(u, 1);
1248 }
1249 else {
1250 v = u;
1251 }
1252 if (v != item) {
1253 Py_INCREF(v);
1254 PyTuple_SET_ITEM(o, i, v);
1255 Py_DECREF(item);
1256 }
1257
1258 Py_DECREF(u);
1259 }
1260 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001262 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001263 // constant keys.
1264 // See _PyCode_ConstantKey() for detail.
1265 assert(PyTuple_CheckExact(key));
1266 assert(PyTuple_GET_SIZE(key) == 2);
1267
1268 Py_ssize_t len = PySet_GET_SIZE(o);
1269 if (len == 0) { // empty frozenset should not be re-created.
1270 return key;
1271 }
1272 PyObject *tuple = PyTuple_New(len);
1273 if (tuple == NULL) {
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 Py_ssize_t i = 0, pos = 0;
1278 PyObject *item;
1279 Py_hash_t hash;
1280 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1281 PyObject *k = merge_consts_recursive(c, item);
1282 if (k == NULL) {
1283 Py_DECREF(tuple);
1284 Py_DECREF(key);
1285 return NULL;
1286 }
1287 PyObject *u;
1288 if (PyTuple_CheckExact(k)) {
1289 u = PyTuple_GET_ITEM(k, 1);
1290 Py_INCREF(u);
1291 Py_DECREF(k);
1292 }
1293 else {
1294 u = k;
1295 }
1296 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1297 i++;
1298 }
1299
1300 // Instead of rewriting o, we create new frozenset and embed in the
1301 // key tuple. Caller should get merged frozenset from the key tuple.
1302 PyObject *new = PyFrozenSet_New(tuple);
1303 Py_DECREF(tuple);
1304 if (new == NULL) {
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 assert(PyTuple_GET_ITEM(key, 1) == o);
1309 Py_DECREF(o);
1310 PyTuple_SET_ITEM(key, 1, new);
1311 }
INADA Naokic2e16072018-11-26 21:23:22 +09001312
1313 return key;
1314}
1315
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316static Py_ssize_t
1317compiler_add_const(struct compiler *c, PyObject *o)
1318{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001319 if (c->c_do_not_emit_bytecode) {
1320 return 0;
1321 }
1322
INADA Naokic2e16072018-11-26 21:23:22 +09001323 PyObject *key = merge_consts_recursive(c, o);
1324 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001326 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001327
INADA Naokic2e16072018-11-26 21:23:22 +09001328 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1329 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
1333static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001334compiler_addop_load_const(struct compiler *c, PyObject *o)
1335{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001336 if (c->c_do_not_emit_bytecode) {
1337 return 1;
1338 }
1339
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001340 Py_ssize_t arg = compiler_add_const(c, o);
1341 if (arg < 0)
1342 return 0;
1343 return compiler_addop_i(c, LOAD_CONST, arg);
1344}
1345
1346static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001350 if (c->c_do_not_emit_bytecode) {
1351 return 1;
1352 }
1353
Victor Stinnerad9a0662013-11-19 22:23:20 +01001354 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 return compiler_addop_i(c, opcode, arg);
1358}
1359
1360static int
1361compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001364 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001365
1366 if (c->c_do_not_emit_bytecode) {
1367 return 1;
1368 }
1369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1371 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001372 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 arg = compiler_add_o(c, dict, mangled);
1374 Py_DECREF(mangled);
1375 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001376 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 return compiler_addop_i(c, opcode, arg);
1378}
1379
1380/* Add an opcode with an integer argument.
1381 Returns 0 on failure, 1 on success.
1382*/
1383
1384static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001385compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 struct instr *i;
1388 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001389
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001390 if (c->c_do_not_emit_bytecode) {
1391 return 1;
1392 }
1393
Victor Stinner2ad474b2016-03-01 23:34:47 +01001394 /* oparg value is unsigned, but a signed C int is usually used to store
1395 it in the C code (like Python/ceval.c).
1396
1397 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1398
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001399 The argument of a concrete bytecode instruction is limited to 8-bit.
1400 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1401 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001402 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 off = compiler_next_instr(c, c->u->u_curblock);
1405 if (off < 0)
1406 return 0;
1407 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001408 i->i_opcode = opcode;
1409 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 compiler_set_lineno(c, off);
1411 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412}
1413
1414static int
1415compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 struct instr *i;
1418 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001420 if (c->c_do_not_emit_bytecode) {
1421 return 1;
1422 }
1423
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001424 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(b != NULL);
1426 off = compiler_next_instr(c, c->u->u_curblock);
1427 if (off < 0)
1428 return 0;
1429 i = &c->u->u_curblock->b_instr[off];
1430 i->i_opcode = opcode;
1431 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (absolute)
1433 i->i_jabs = 1;
1434 else
1435 i->i_jrel = 1;
1436 compiler_set_lineno(c, off);
1437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438}
1439
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001440/* NEXT_BLOCK() creates an implicit jump from the current block
1441 to the new block.
1442
1443 The returns inside this macro make it impossible to decref objects
1444 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (compiler_next_block((C)) == NULL) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
1451#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) \
1453 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454}
1455
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop((C), (OP))) { \
1458 compiler_exit_scope(c); \
1459 return 0; \
1460 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001461}
1462
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001463#define ADDOP_LOAD_CONST(C, O) { \
1464 if (!compiler_addop_load_const((C), (O))) \
1465 return 0; \
1466}
1467
1468/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1469#define ADDOP_LOAD_CONST_NEW(C, O) { \
1470 PyObject *__new_const = (O); \
1471 if (__new_const == NULL) { \
1472 return 0; \
1473 } \
1474 if (!compiler_addop_load_const((C), __new_const)) { \
1475 Py_DECREF(__new_const); \
1476 return 0; \
1477 } \
1478 Py_DECREF(__new_const); \
1479}
1480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1483 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484}
1485
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001486/* Same as ADDOP_O, but steals a reference. */
1487#define ADDOP_N(C, OP, O, TYPE) { \
1488 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1489 Py_DECREF((O)); \
1490 return 0; \
1491 } \
1492 Py_DECREF((O)); \
1493}
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_i((C), (OP), (O))) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_addop_j((C), (OP), (O), 1)) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
1510#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!compiler_addop_j((C), (OP), (O), 0)) \
1512 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513}
1514
1515/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1516 the ASDL name to synthesize the name of the C type and the visit function.
1517*/
1518
1519#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) \
1521 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522}
1523
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_visit_ ## TYPE((C), (V))) { \
1526 compiler_exit_scope(c); \
1527 return 0; \
1528 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001529}
1530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (!compiler_visit_slice((C), (V), (CTX))) \
1533 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int _i; \
1538 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1539 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1540 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1541 if (!compiler_visit_ ## TYPE((C), elt)) \
1542 return 0; \
1543 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544}
1545
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int _i; \
1548 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1549 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1550 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1551 if (!compiler_visit_ ## TYPE((C), elt)) { \
1552 compiler_exit_scope(c); \
1553 return 0; \
1554 } \
1555 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001556}
1557
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001558/* These macros allows to check only for errors and not emmit bytecode
1559 * while visiting nodes.
1560*/
1561
1562#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1563 c->c_do_not_emit_bytecode++;
1564
1565#define END_DO_NOT_EMIT_BYTECODE \
1566 c->c_do_not_emit_bytecode--; \
1567}
1568
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001569/* Search if variable annotations are present statically in a block. */
1570
1571static int
1572find_ann(asdl_seq *stmts)
1573{
1574 int i, j, res = 0;
1575 stmt_ty st;
1576
1577 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1578 st = (stmt_ty)asdl_seq_GET(stmts, i);
1579 switch (st->kind) {
1580 case AnnAssign_kind:
1581 return 1;
1582 case For_kind:
1583 res = find_ann(st->v.For.body) ||
1584 find_ann(st->v.For.orelse);
1585 break;
1586 case AsyncFor_kind:
1587 res = find_ann(st->v.AsyncFor.body) ||
1588 find_ann(st->v.AsyncFor.orelse);
1589 break;
1590 case While_kind:
1591 res = find_ann(st->v.While.body) ||
1592 find_ann(st->v.While.orelse);
1593 break;
1594 case If_kind:
1595 res = find_ann(st->v.If.body) ||
1596 find_ann(st->v.If.orelse);
1597 break;
1598 case With_kind:
1599 res = find_ann(st->v.With.body);
1600 break;
1601 case AsyncWith_kind:
1602 res = find_ann(st->v.AsyncWith.body);
1603 break;
1604 case Try_kind:
1605 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1606 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1607 st->v.Try.handlers, j);
1608 if (find_ann(handler->v.ExceptHandler.body)) {
1609 return 1;
1610 }
1611 }
1612 res = find_ann(st->v.Try.body) ||
1613 find_ann(st->v.Try.finalbody) ||
1614 find_ann(st->v.Try.orelse);
1615 break;
1616 default:
1617 res = 0;
1618 }
1619 if (res) {
1620 break;
1621 }
1622 }
1623 return res;
1624}
1625
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001626/*
1627 * Frame block handling functions
1628 */
1629
1630static int
1631compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1632 basicblock *exit)
1633{
1634 struct fblockinfo *f;
1635 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1636 PyErr_SetString(PyExc_SyntaxError,
1637 "too many statically nested blocks");
1638 return 0;
1639 }
1640 f = &c->u->u_fblock[c->u->u_nfblocks++];
1641 f->fb_type = t;
1642 f->fb_block = b;
1643 f->fb_exit = exit;
1644 return 1;
1645}
1646
1647static void
1648compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1649{
1650 struct compiler_unit *u = c->u;
1651 assert(u->u_nfblocks > 0);
1652 u->u_nfblocks--;
1653 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1654 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1655}
1656
1657/* Unwind a frame block. If preserve_tos is true, the TOS before
1658 * popping the blocks will be restored afterwards.
1659 */
1660static int
1661compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1662 int preserve_tos)
1663{
1664 switch (info->fb_type) {
1665 case WHILE_LOOP:
1666 return 1;
1667
1668 case FINALLY_END:
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001669 info->fb_exit = NULL;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001670 ADDOP_I(c, POP_FINALLY, preserve_tos);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001671 if (preserve_tos) {
1672 ADDOP(c, ROT_TWO);
1673 }
1674 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001675 return 1;
1676
1677 case FOR_LOOP:
1678 /* Pop the iterator */
1679 if (preserve_tos) {
1680 ADDOP(c, ROT_TWO);
1681 }
1682 ADDOP(c, POP_TOP);
1683 return 1;
1684
1685 case EXCEPT:
1686 ADDOP(c, POP_BLOCK);
1687 return 1;
1688
1689 case FINALLY_TRY:
1690 ADDOP(c, POP_BLOCK);
1691 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1692 return 1;
1693
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001694 case FINALLY_TRY2:
1695 ADDOP(c, POP_BLOCK);
1696 if (preserve_tos) {
1697 ADDOP(c, ROT_TWO);
1698 ADDOP(c, POP_TOP);
1699 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1700 }
1701 else {
1702 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1703 ADDOP(c, POP_TOP);
1704 }
1705 return 1;
1706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 case WITH:
1708 case ASYNC_WITH:
1709 ADDOP(c, POP_BLOCK);
1710 if (preserve_tos) {
1711 ADDOP(c, ROT_TWO);
1712 }
1713 ADDOP(c, BEGIN_FINALLY);
1714 ADDOP(c, WITH_CLEANUP_START);
1715 if (info->fb_type == ASYNC_WITH) {
1716 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001717 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001718 ADDOP(c, YIELD_FROM);
1719 }
1720 ADDOP(c, WITH_CLEANUP_FINISH);
1721 ADDOP_I(c, POP_FINALLY, 0);
1722 return 1;
1723
1724 case HANDLER_CLEANUP:
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_FOUR);
1727 }
1728 if (info->fb_exit) {
1729 ADDOP(c, POP_BLOCK);
1730 ADDOP(c, POP_EXCEPT);
1731 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1732 }
1733 else {
1734 ADDOP(c, POP_EXCEPT);
1735 }
1736 return 1;
1737 }
1738 Py_UNREACHABLE();
1739}
1740
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001741/* Compile a sequence of statements, checking for a docstring
1742 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743
1744static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001745compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001746{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001747 int i = 0;
1748 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001749 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001750
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001751 /* Set current line number to the line number of first statement.
1752 This way line number for SETUP_ANNOTATIONS will always
1753 coincide with the line number of first "real" statement in module.
1754 If body is empy, then lineno will be set later in assemble. */
1755 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1756 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001757 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001758 c->u->u_lineno = st->lineno;
1759 }
1760 /* Every annotated class and module should have __annotations__. */
1761 if (find_ann(stmts)) {
1762 ADDOP(c, SETUP_ANNOTATIONS);
1763 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001764 if (!asdl_seq_LEN(stmts))
1765 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001766 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001767 if (c->c_optimize < 2) {
1768 docstring = _PyAST_GetDocString(stmts);
1769 if (docstring) {
1770 i = 1;
1771 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1772 assert(st->kind == Expr_kind);
1773 VISIT(c, expr, st->v.Expr.value);
1774 if (!compiler_nameop(c, __doc__, Store))
1775 return 0;
1776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001778 for (; i < asdl_seq_LEN(stmts); i++)
1779 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781}
1782
1783static PyCodeObject *
1784compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCodeObject *co;
1787 int addNone = 1;
1788 static PyObject *module;
1789 if (!module) {
1790 module = PyUnicode_InternFromString("<module>");
1791 if (!module)
1792 return NULL;
1793 }
1794 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001795 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return NULL;
1797 switch (mod->kind) {
1798 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001799 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 compiler_exit_scope(c);
1801 return 0;
1802 }
1803 break;
1804 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001805 if (find_ann(mod->v.Interactive.body)) {
1806 ADDOP(c, SETUP_ANNOTATIONS);
1807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 c->c_interactive = 1;
1809 VISIT_SEQ_IN_SCOPE(c, stmt,
1810 mod->v.Interactive.body);
1811 break;
1812 case Expression_kind:
1813 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1814 addNone = 0;
1815 break;
1816 case Suite_kind:
1817 PyErr_SetString(PyExc_SystemError,
1818 "suite should not be possible");
1819 return 0;
1820 default:
1821 PyErr_Format(PyExc_SystemError,
1822 "module kind %d should not be possible",
1823 mod->kind);
1824 return 0;
1825 }
1826 co = assemble(c, addNone);
1827 compiler_exit_scope(c);
1828 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001829}
1830
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831/* The test for LOCAL must come before the test for FREE in order to
1832 handle classes where name is both local and free. The local var is
1833 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001834*/
1835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836static int
1837get_ref_type(struct compiler *c, PyObject *name)
1838{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001839 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001840 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001841 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001842 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001843 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (scope == 0) {
1845 char buf[350];
1846 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001847 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001849 PyUnicode_AsUTF8(name),
1850 PyUnicode_AsUTF8(c->u->u_name),
1851 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1852 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1853 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1854 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 );
1856 Py_FatalError(buf);
1857 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860}
1861
1862static int
1863compiler_lookup_arg(PyObject *dict, PyObject *name)
1864{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001865 PyObject *v;
1866 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001868 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001869 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870}
1871
1872static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001873compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001875 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001876 if (qualname == NULL)
1877 qualname = co->co_name;
1878
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001879 if (free) {
1880 for (i = 0; i < free; ++i) {
1881 /* Bypass com_addop_varname because it will generate
1882 LOAD_DEREF but LOAD_CLOSURE is needed.
1883 */
1884 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1885 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001887 /* Special case: If a class contains a method with a
1888 free variable that has the same name as a method,
1889 the name will be considered free *and* local in the
1890 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001891 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001892 */
1893 reftype = get_ref_type(c, name);
1894 if (reftype == CELL)
1895 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1896 else /* (reftype == FREE) */
1897 arg = compiler_lookup_arg(c->u->u_freevars, name);
1898 if (arg == -1) {
1899 fprintf(stderr,
1900 "lookup %s in %s %d %d\n"
1901 "freevars of %s: %s\n",
1902 PyUnicode_AsUTF8(PyObject_Repr(name)),
1903 PyUnicode_AsUTF8(c->u->u_name),
1904 reftype, arg,
1905 PyUnicode_AsUTF8(co->co_name),
1906 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1907 Py_FatalError("compiler_make_closure()");
1908 }
1909 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 flags |= 0x08;
1912 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 ADDOP_LOAD_CONST(c, (PyObject*)co);
1915 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918}
1919
1920static int
1921compiler_decorators(struct compiler *c, asdl_seq* decos)
1922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (!decos)
1926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1929 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1930 }
1931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
1934static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001935compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001937{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001938 /* Push a dict of keyword-only default values.
1939
1940 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1941 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001942 int i;
1943 PyObject *keys = NULL;
1944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1946 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1947 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1948 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001949 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001950 if (!mangled) {
1951 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 if (keys == NULL) {
1954 keys = PyList_New(1);
1955 if (keys == NULL) {
1956 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001957 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001958 }
1959 PyList_SET_ITEM(keys, 0, mangled);
1960 }
1961 else {
1962 int res = PyList_Append(keys, mangled);
1963 Py_DECREF(mangled);
1964 if (res == -1) {
1965 goto error;
1966 }
1967 }
1968 if (!compiler_visit_expr(c, default_)) {
1969 goto error;
1970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 }
1972 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001973 if (keys != NULL) {
1974 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1975 PyObject *keys_tuple = PyList_AsTuple(keys);
1976 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001977 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001978 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001979 assert(default_count > 0);
1980 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001981 }
1982 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001983 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001984 }
1985
1986error:
1987 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001988 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001989}
1990
1991static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001992compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1993{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001994 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001995 return 1;
1996}
1997
1998static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001999compiler_visit_argannotation(struct compiler *c, identifier id,
2000 expr_ty annotation, PyObject *names)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002003 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002004 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2005 VISIT(c, annexpr, annotation)
2006 }
2007 else {
2008 VISIT(c, expr, annotation);
2009 }
Victor Stinner065efc32014-02-18 22:07:56 +01002010 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002011 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002012 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002013 if (PyList_Append(names, mangled) < 0) {
2014 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002015 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002016 }
2017 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002019 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002020}
2021
2022static int
2023compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2024 PyObject *names)
2025{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002026 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 for (i = 0; i < asdl_seq_LEN(args); i++) {
2028 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002029 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 c,
2031 arg->arg,
2032 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002033 names))
2034 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002036 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002037}
2038
2039static int
2040compiler_visit_annotations(struct compiler *c, arguments_ty args,
2041 expr_ty returns)
2042{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002043 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002044 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002045
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002046 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 */
2048 static identifier return_str;
2049 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002050 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 names = PyList_New(0);
2052 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002053 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002054
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002055 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002057 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2058 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002059 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002061 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002065 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002067 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (!return_str) {
2071 return_str = PyUnicode_InternFromString("return");
2072 if (!return_str)
2073 goto error;
2074 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 goto error;
2077 }
2078
2079 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002081 PyObject *keytuple = PyList_AsTuple(names);
2082 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002083 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002084 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002085 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002087 else {
2088 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002089 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002090 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002091
2092error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002094 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002095}
2096
2097static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002098compiler_visit_defaults(struct compiler *c, arguments_ty args)
2099{
2100 VISIT_SEQ(c, expr, args->defaults);
2101 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2102 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103}
2104
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105static Py_ssize_t
2106compiler_default_arguments(struct compiler *c, arguments_ty args)
2107{
2108 Py_ssize_t funcflags = 0;
2109 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110 if (!compiler_visit_defaults(c, args))
2111 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 funcflags |= 0x01;
2113 }
2114 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002115 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002117 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 return -1;
2119 }
2120 else if (res > 0) {
2121 funcflags |= 0x02;
2122 }
2123 }
2124 return funcflags;
2125}
2126
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127static int
Yury Selivanov75445082015-05-11 22:57:16 -04002128compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002131 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002132 arguments_ty args;
2133 expr_ty returns;
2134 identifier name;
2135 asdl_seq* decos;
2136 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002137 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002139 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002140 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
Yury Selivanov75445082015-05-11 22:57:16 -04002142 if (is_async) {
2143 assert(s->kind == AsyncFunctionDef_kind);
2144
2145 args = s->v.AsyncFunctionDef.args;
2146 returns = s->v.AsyncFunctionDef.returns;
2147 decos = s->v.AsyncFunctionDef.decorator_list;
2148 name = s->v.AsyncFunctionDef.name;
2149 body = s->v.AsyncFunctionDef.body;
2150
2151 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2152 } else {
2153 assert(s->kind == FunctionDef_kind);
2154
2155 args = s->v.FunctionDef.args;
2156 returns = s->v.FunctionDef.returns;
2157 decos = s->v.FunctionDef.decorator_list;
2158 name = s->v.FunctionDef.name;
2159 body = s->v.FunctionDef.body;
2160
2161 scope_type = COMPILER_SCOPE_FUNCTION;
2162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (!compiler_decorators(c, decos))
2165 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002166
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002167 firstlineno = s->lineno;
2168 if (asdl_seq_LEN(decos)) {
2169 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2170 }
2171
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002172 funcflags = compiler_default_arguments(c, args);
2173 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002175 }
2176
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002177 annotations = compiler_visit_annotations(c, args, returns);
2178 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002179 return 0;
2180 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002181 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002182 funcflags |= 0x04;
2183 }
2184
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002185 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002186 return 0;
2187 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188
INADA Naokicb41b272017-02-23 00:31:59 +09002189 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002190 if (c->c_optimize < 2) {
2191 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002192 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002193 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 compiler_exit_scope(c);
2195 return 0;
2196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002199 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002201 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002203 qualname = c->u->u_qualname;
2204 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002206 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002207 Py_XDECREF(qualname);
2208 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002212 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002213 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* decorators */
2217 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2218 ADDOP_I(c, CALL_FUNCTION, 1);
2219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220
Yury Selivanov75445082015-05-11 22:57:16 -04002221 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222}
2223
2224static int
2225compiler_class(struct compiler *c, stmt_ty s)
2226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyCodeObject *co;
2228 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002229 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (!compiler_decorators(c, decos))
2233 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002234
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002235 firstlineno = s->lineno;
2236 if (asdl_seq_LEN(decos)) {
2237 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2238 }
2239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* ultimately generate code for:
2241 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2242 where:
2243 <func> is a function/closure created from the class body;
2244 it has a single argument (__locals__) where the dict
2245 (or MutableSequence) representing the locals is passed
2246 <name> is the class name
2247 <bases> is the positional arguments and *varargs argument
2248 <keywords> is the keyword arguments and **kwds argument
2249 This borrows from compiler_call.
2250 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002253 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002254 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 return 0;
2256 /* this block represents what we do in the new scope */
2257 {
2258 /* use the class name for name mangling */
2259 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002260 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* load (global) __name__ ... */
2262 str = PyUnicode_InternFromString("__name__");
2263 if (!str || !compiler_nameop(c, str, Load)) {
2264 Py_XDECREF(str);
2265 compiler_exit_scope(c);
2266 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Py_DECREF(str);
2269 /* ... and store it as __module__ */
2270 str = PyUnicode_InternFromString("__module__");
2271 if (!str || !compiler_nameop(c, str, Store)) {
2272 Py_XDECREF(str);
2273 compiler_exit_scope(c);
2274 return 0;
2275 }
2276 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002277 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002278 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002279 str = PyUnicode_InternFromString("__qualname__");
2280 if (!str || !compiler_nameop(c, str, Store)) {
2281 Py_XDECREF(str);
2282 compiler_exit_scope(c);
2283 return 0;
2284 }
2285 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002287 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 compiler_exit_scope(c);
2289 return 0;
2290 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002291 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002292 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002293 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002294 str = PyUnicode_InternFromString("__class__");
2295 if (str == NULL) {
2296 compiler_exit_scope(c);
2297 return 0;
2298 }
2299 i = compiler_lookup_arg(c->u->u_cellvars, str);
2300 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002301 if (i < 0) {
2302 compiler_exit_scope(c);
2303 return 0;
2304 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002305 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002308 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002309 str = PyUnicode_InternFromString("__classcell__");
2310 if (!str || !compiler_nameop(c, str, Store)) {
2311 Py_XDECREF(str);
2312 compiler_exit_scope(c);
2313 return 0;
2314 }
2315 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002317 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002318 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002319 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002320 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002321 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002322 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* create the code object */
2324 co = assemble(c, 1);
2325 }
2326 /* leave the new scope */
2327 compiler_exit_scope(c);
2328 if (co == NULL)
2329 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* 2. load the 'build_class' function */
2332 ADDOP(c, LOAD_BUILD_CLASS);
2333
2334 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002335 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 Py_DECREF(co);
2337
2338 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002339 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340
2341 /* 5. generate the rest of the code for the call */
2342 if (!compiler_call_helper(c, 2,
2343 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002344 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return 0;
2346
2347 /* 6. apply decorators */
2348 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2349 ADDOP_I(c, CALL_FUNCTION, 1);
2350 }
2351
2352 /* 7. store into <name> */
2353 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2354 return 0;
2355 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356}
2357
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002358/* Return 0 if the expression is a constant value except named singletons.
2359 Return 1 otherwise. */
2360static int
2361check_is_arg(expr_ty e)
2362{
2363 if (e->kind != Constant_kind) {
2364 return 1;
2365 }
2366 PyObject *value = e->v.Constant.value;
2367 return (value == Py_None
2368 || value == Py_False
2369 || value == Py_True
2370 || value == Py_Ellipsis);
2371}
2372
2373/* Check operands of identity chacks ("is" and "is not").
2374 Emit a warning if any operand is a constant except named singletons.
2375 Return 0 on error.
2376 */
2377static int
2378check_compare(struct compiler *c, expr_ty e)
2379{
2380 Py_ssize_t i, n;
2381 int left = check_is_arg(e->v.Compare.left);
2382 n = asdl_seq_LEN(e->v.Compare.ops);
2383 for (i = 0; i < n; i++) {
2384 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2385 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2386 if (op == Is || op == IsNot) {
2387 if (!right || !left) {
2388 const char *msg = (op == Is)
2389 ? "\"is\" with a literal. Did you mean \"==\"?"
2390 : "\"is not\" with a literal. Did you mean \"!=\"?";
2391 return compiler_warn(c, msg);
2392 }
2393 }
2394 left = right;
2395 }
2396 return 1;
2397}
2398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002400cmpop(cmpop_ty op)
2401{
2402 switch (op) {
2403 case Eq:
2404 return PyCmp_EQ;
2405 case NotEq:
2406 return PyCmp_NE;
2407 case Lt:
2408 return PyCmp_LT;
2409 case LtE:
2410 return PyCmp_LE;
2411 case Gt:
2412 return PyCmp_GT;
2413 case GtE:
2414 return PyCmp_GE;
2415 case Is:
2416 return PyCmp_IS;
2417 case IsNot:
2418 return PyCmp_IS_NOT;
2419 case In:
2420 return PyCmp_IN;
2421 case NotIn:
2422 return PyCmp_NOT_IN;
2423 default:
2424 return PyCmp_BAD;
2425 }
2426}
2427
2428static int
2429compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2430{
2431 switch (e->kind) {
2432 case UnaryOp_kind:
2433 if (e->v.UnaryOp.op == Not)
2434 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2435 /* fallback to general implementation */
2436 break;
2437 case BoolOp_kind: {
2438 asdl_seq *s = e->v.BoolOp.values;
2439 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2440 assert(n >= 0);
2441 int cond2 = e->v.BoolOp.op == Or;
2442 basicblock *next2 = next;
2443 if (!cond2 != !cond) {
2444 next2 = compiler_new_block(c);
2445 if (next2 == NULL)
2446 return 0;
2447 }
2448 for (i = 0; i < n; ++i) {
2449 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2450 return 0;
2451 }
2452 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2453 return 0;
2454 if (next2 != next)
2455 compiler_use_next_block(c, next2);
2456 return 1;
2457 }
2458 case IfExp_kind: {
2459 basicblock *end, *next2;
2460 end = compiler_new_block(c);
2461 if (end == NULL)
2462 return 0;
2463 next2 = compiler_new_block(c);
2464 if (next2 == NULL)
2465 return 0;
2466 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2467 return 0;
2468 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2469 return 0;
2470 ADDOP_JREL(c, JUMP_FORWARD, end);
2471 compiler_use_next_block(c, next2);
2472 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2473 return 0;
2474 compiler_use_next_block(c, end);
2475 return 1;
2476 }
2477 case Compare_kind: {
2478 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2479 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002480 if (!check_compare(c, e)) {
2481 return 0;
2482 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 basicblock *cleanup = compiler_new_block(c);
2484 if (cleanup == NULL)
2485 return 0;
2486 VISIT(c, expr, e->v.Compare.left);
2487 for (i = 0; i < n; i++) {
2488 VISIT(c, expr,
2489 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2490 ADDOP(c, DUP_TOP);
2491 ADDOP(c, ROT_THREE);
2492 ADDOP_I(c, COMPARE_OP,
2493 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2494 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2495 NEXT_BLOCK(c);
2496 }
2497 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2498 ADDOP_I(c, COMPARE_OP,
2499 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2500 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2501 basicblock *end = compiler_new_block(c);
2502 if (end == NULL)
2503 return 0;
2504 ADDOP_JREL(c, JUMP_FORWARD, end);
2505 compiler_use_next_block(c, cleanup);
2506 ADDOP(c, POP_TOP);
2507 if (!cond) {
2508 ADDOP_JREL(c, JUMP_FORWARD, next);
2509 }
2510 compiler_use_next_block(c, end);
2511 return 1;
2512 }
2513 /* fallback to general implementation */
2514 break;
2515 }
2516 default:
2517 /* fallback to general implementation */
2518 break;
2519 }
2520
2521 /* general implementation */
2522 VISIT(c, expr, e);
2523 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2524 return 1;
2525}
2526
2527static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002528compiler_ifexp(struct compiler *c, expr_ty e)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 basicblock *end, *next;
2531
2532 assert(e->kind == IfExp_kind);
2533 end = compiler_new_block(c);
2534 if (end == NULL)
2535 return 0;
2536 next = compiler_new_block(c);
2537 if (next == NULL)
2538 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002539 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2540 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 VISIT(c, expr, e->v.IfExp.body);
2542 ADDOP_JREL(c, JUMP_FORWARD, end);
2543 compiler_use_next_block(c, next);
2544 VISIT(c, expr, e->v.IfExp.orelse);
2545 compiler_use_next_block(c, end);
2546 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002547}
2548
2549static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550compiler_lambda(struct compiler *c, expr_ty e)
2551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002553 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002555 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 arguments_ty args = e->v.Lambda.args;
2557 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (!name) {
2560 name = PyUnicode_InternFromString("<lambda>");
2561 if (!name)
2562 return 0;
2563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002565 funcflags = compiler_default_arguments(c, args);
2566 if (funcflags == -1) {
2567 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002569
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002570 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002571 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* Make None the first constant, so the lambda can't have a
2575 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002576 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002580 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2582 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2583 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002584 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 }
2586 else {
2587 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002588 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002590 qualname = c->u->u_qualname;
2591 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002593 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002596 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002597 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 Py_DECREF(co);
2599
2600 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601}
2602
2603static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604compiler_if(struct compiler *c, stmt_ty s)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 basicblock *end, *next;
2607 int constant;
2608 assert(s->kind == If_kind);
2609 end = compiler_new_block(c);
2610 if (end == NULL)
2611 return 0;
2612
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002613 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002614 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 * constant = 1: "if 1", "if 2", ...
2616 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002617 if (constant == 0) {
2618 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002620 END_DO_NOT_EMIT_BYTECODE
2621 if (s->v.If.orelse) {
2622 VISIT_SEQ(c, stmt, s->v.If.orelse);
2623 }
2624 } else if (constant == 1) {
2625 VISIT_SEQ(c, stmt, s->v.If.body);
2626 if (s->v.If.orelse) {
2627 BEGIN_DO_NOT_EMIT_BYTECODE
2628 VISIT_SEQ(c, stmt, s->v.If.orelse);
2629 END_DO_NOT_EMIT_BYTECODE
2630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002632 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 next = compiler_new_block(c);
2634 if (next == NULL)
2635 return 0;
2636 }
2637 else
2638 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002639 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2640 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002642 if (asdl_seq_LEN(s->v.If.orelse)) {
2643 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 compiler_use_next_block(c, next);
2645 VISIT_SEQ(c, stmt, s->v.If.orelse);
2646 }
2647 }
2648 compiler_use_next_block(c, end);
2649 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650}
2651
2652static int
2653compiler_for(struct compiler *c, stmt_ty s)
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 start = compiler_new_block(c);
2658 cleanup = compiler_new_block(c);
2659 end = compiler_new_block(c);
2660 if (start == NULL || end == NULL || cleanup == NULL)
2661 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002662
2663 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 VISIT(c, expr, s->v.For.iter);
2667 ADDOP(c, GET_ITER);
2668 compiler_use_next_block(c, start);
2669 ADDOP_JREL(c, FOR_ITER, cleanup);
2670 VISIT(c, expr, s->v.For.target);
2671 VISIT_SEQ(c, stmt, s->v.For.body);
2672 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2673 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002674
2675 compiler_pop_fblock(c, FOR_LOOP, start);
2676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 VISIT_SEQ(c, stmt, s->v.For.orelse);
2678 compiler_use_next_block(c, end);
2679 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680}
2681
Yury Selivanov75445082015-05-11 22:57:16 -04002682
2683static int
2684compiler_async_for(struct compiler *c, stmt_ty s)
2685{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002686 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002687 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2688 c->u->u_ste->ste_coroutine = 1;
2689 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002690 return compiler_error(c, "'async for' outside async function");
2691 }
2692
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002693 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002694 except = compiler_new_block(c);
2695 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002696
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002697 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002698 return 0;
2699
2700 VISIT(c, expr, s->v.AsyncFor.iter);
2701 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002702
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002703 compiler_use_next_block(c, start);
2704 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2705 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002707 /* SETUP_FINALLY to guard the __anext__ call */
2708 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002709 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002710 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002711 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002712 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002713
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002714 /* Success block for __anext__ */
2715 VISIT(c, expr, s->v.AsyncFor.target);
2716 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2717 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2718
2719 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002720
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002721 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002722 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002723 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002724
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002725 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002726 VISIT_SEQ(c, stmt, s->v.For.orelse);
2727
2728 compiler_use_next_block(c, end);
2729
2730 return 1;
2731}
2732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733static int
2734compiler_while(struct compiler *c, stmt_ty s)
2735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002737 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002740 BEGIN_DO_NOT_EMIT_BYTECODE
2741 VISIT_SEQ(c, stmt, s->v.While.body);
2742 END_DO_NOT_EMIT_BYTECODE
2743 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 return 1;
2747 }
2748 loop = compiler_new_block(c);
2749 end = compiler_new_block(c);
2750 if (constant == -1) {
2751 anchor = compiler_new_block(c);
2752 if (anchor == NULL)
2753 return 0;
2754 }
2755 if (loop == NULL || end == NULL)
2756 return 0;
2757 if (s->v.While.orelse) {
2758 orelse = compiler_new_block(c);
2759 if (orelse == NULL)
2760 return 0;
2761 }
2762 else
2763 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002766 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 0;
2768 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002769 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2770 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 }
2772 VISIT_SEQ(c, stmt, s->v.While.body);
2773 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* XXX should the two POP instructions be in a separate block
2776 if there is no else clause ?
2777 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002779 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002781 compiler_pop_fblock(c, WHILE_LOOP, loop);
2782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 if (orelse != NULL) /* what if orelse is just pass? */
2784 VISIT_SEQ(c, stmt, s->v.While.orelse);
2785 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788}
2789
2790static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002791compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002794 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002795 if (c->u->u_ste->ste_type != FunctionBlock)
2796 return compiler_error(c, "'return' outside function");
2797 if (s->v.Return.value != NULL &&
2798 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2799 {
2800 return compiler_error(
2801 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 if (preserve_tos) {
2804 VISIT(c, expr, s->v.Return.value);
2805 }
2806 for (int depth = c->u->u_nfblocks; depth--;) {
2807 struct fblockinfo *info = &c->u->u_fblock[depth];
2808
2809 if (!compiler_unwind_fblock(c, info, preserve_tos))
2810 return 0;
2811 }
2812 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002813 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002814 }
2815 else if (!preserve_tos) {
2816 VISIT(c, expr, s->v.Return.value);
2817 }
2818 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821}
2822
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002823static int
2824compiler_break(struct compiler *c)
2825{
2826 for (int depth = c->u->u_nfblocks; depth--;) {
2827 struct fblockinfo *info = &c->u->u_fblock[depth];
2828
2829 if (!compiler_unwind_fblock(c, info, 0))
2830 return 0;
2831 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2832 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2833 return 1;
2834 }
2835 }
2836 return compiler_error(c, "'break' outside loop");
2837}
2838
2839static int
2840compiler_continue(struct compiler *c)
2841{
2842 for (int depth = c->u->u_nfblocks; depth--;) {
2843 struct fblockinfo *info = &c->u->u_fblock[depth];
2844
2845 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2846 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2847 return 1;
2848 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002849 if (!compiler_unwind_fblock(c, info, 0))
2850 return 0;
2851 }
2852 return compiler_error(c, "'continue' not properly in loop");
2853}
2854
2855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857
2858 SETUP_FINALLY L
2859 <code for body>
2860 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002861 BEGIN_FINALLY
2862 L:
2863 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 END_FINALLY
2865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 The special instructions use the block stack. Each block
2867 stack entry contains the instruction that created it (here
2868 SETUP_FINALLY), the level of the value stack at the time the
2869 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 Pushes the current value stack level and the label
2873 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 Pops en entry from the block stack.
2876 BEGIN_FINALLY
2877 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2880 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 when a SETUP_FINALLY entry is found, the raised and the caught
2884 exceptions are pushed onto the value stack (and the exception
2885 condition is cleared), and the interpreter jumps to the label
2886 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887*/
2888
2889static int
2890compiler_try_finally(struct compiler *c, stmt_ty s)
2891{
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002892 basicblock *start, *newcurblock, *body, *end;
2893 int break_finally = 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 body = compiler_new_block(c);
2896 end = compiler_new_block(c);
2897 if (body == NULL || end == NULL)
2898 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002900 start = c->u->u_curblock;
2901
2902 /* `finally` block. Compile it first to determine if any of "break",
2903 "continue" or "return" are used in it. */
2904 compiler_use_next_block(c, end);
2905 if (!compiler_push_fblock(c, FINALLY_END, end, end))
2906 return 0;
2907 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2908 ADDOP(c, END_FINALLY);
2909 break_finally = (c->u->u_fblock[c->u->u_nfblocks - 1].fb_exit == NULL);
2910 if (break_finally) {
2911 /* Pops a placeholder. See below */
2912 ADDOP(c, POP_TOP);
2913 }
2914 compiler_pop_fblock(c, FINALLY_END, end);
2915
2916 newcurblock = c->u->u_curblock;
2917 c->u->u_curblock = start;
2918 start->b_next = NULL;
2919
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002920 /* `try` block */
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002921 c->u->u_lineno_set = 0;
2922 c->u->u_lineno = s->lineno;
2923 c->u->u_col_offset = s->col_offset;
2924 if (break_finally) {
2925 /* Pushes a placeholder for the value of "return" in the "try" block
2926 to balance the stack for "break", "continue" and "return" in
2927 the "finally" block. */
2928 ADDOP_LOAD_CONST(c, Py_None);
2929 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 ADDOP_JREL(c, SETUP_FINALLY, end);
2931 compiler_use_next_block(c, body);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002932 if (!compiler_push_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002934 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2935 if (!compiler_try_except(c, s))
2936 return 0;
2937 }
2938 else {
2939 VISIT_SEQ(c, stmt, s->v.Try.body);
2940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942 ADDOP(c, BEGIN_FINALLY);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002943 compiler_pop_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002945 c->u->u_curblock->b_next = end;
2946 c->u->u_curblock = newcurblock;
2947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949}
2950
2951/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002952 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 (The contents of the value stack is shown in [], with the top
2954 at the right; 'tb' is trace-back info, 'val' the exception's
2955 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956
2957 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002958 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 [] <code for S>
2960 [] POP_BLOCK
2961 [] JUMP_FORWARD L0
2962
2963 [tb, val, exc] L1: DUP )
2964 [tb, val, exc, exc] <evaluate E1> )
2965 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2966 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2967 [tb, val, exc] POP
2968 [tb, val] <assign to V1> (or POP if no V1)
2969 [tb] POP
2970 [] <code for S1>
2971 JUMP_FORWARD L0
2972
2973 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974 .............................etc.......................
2975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2977
2978 [] L0: <next statement>
2979
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 Of course, parts are not generated if Vi or Ei is not present.
2981*/
2982static int
2983compiler_try_except(struct compiler *c, stmt_ty s)
2984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002986 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 body = compiler_new_block(c);
2989 except = compiler_new_block(c);
2990 orelse = compiler_new_block(c);
2991 end = compiler_new_block(c);
2992 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2993 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002994 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002996 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002998 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 ADDOP(c, POP_BLOCK);
3000 compiler_pop_fblock(c, EXCEPT, body);
3001 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003002 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 compiler_use_next_block(c, except);
3004 for (i = 0; i < n; i++) {
3005 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003006 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 if (!handler->v.ExceptHandler.type && i < n-1)
3008 return compiler_error(c, "default 'except:' must be last");
3009 c->u->u_lineno_set = 0;
3010 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003011 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 except = compiler_new_block(c);
3013 if (except == NULL)
3014 return 0;
3015 if (handler->v.ExceptHandler.type) {
3016 ADDOP(c, DUP_TOP);
3017 VISIT(c, expr, handler->v.ExceptHandler.type);
3018 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3019 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3020 }
3021 ADDOP(c, POP_TOP);
3022 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003023 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003024
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003025 cleanup_end = compiler_new_block(c);
3026 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003027 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003028 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003029 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003030
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003031 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3032 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003034 /*
3035 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003036 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003037 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003038 try:
3039 # body
3040 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003041 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003042 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003043 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003045 /* second try: */
3046 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3047 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003048 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003049 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003051 /* second # body */
3052 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
3053 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003054 ADDOP(c, BEGIN_FINALLY);
3055 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003059 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003060 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003062 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003063 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003064 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02003068 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 }
3071 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003075 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077
Guido van Rossumb940e112007-01-10 16:19:56 +00003078 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 ADDOP(c, POP_TOP);
3080 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003081 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003085 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
3087 ADDOP_JREL(c, JUMP_FORWARD, end);
3088 compiler_use_next_block(c, except);
3089 }
3090 ADDOP(c, END_FINALLY);
3091 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003092 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 compiler_use_next_block(c, end);
3094 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095}
3096
3097static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003098compiler_try(struct compiler *c, stmt_ty s) {
3099 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3100 return compiler_try_finally(c, s);
3101 else
3102 return compiler_try_except(c, s);
3103}
3104
3105
3106static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107compiler_import_as(struct compiler *c, identifier name, identifier asname)
3108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 /* The IMPORT_NAME opcode was already generated. This function
3110 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003113 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003115 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3116 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003117 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003118 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003119 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003121 while (1) {
3122 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003124 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003125 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003126 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003127 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003129 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003130 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003131 if (dot == -1) {
3132 break;
3133 }
3134 ADDOP(c, ROT_TWO);
3135 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003137 if (!compiler_nameop(c, asname, Store)) {
3138 return 0;
3139 }
3140 ADDOP(c, POP_TOP);
3141 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 }
3143 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144}
3145
3146static int
3147compiler_import(struct compiler *c, stmt_ty s)
3148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 /* The Import node stores a module name like a.b.c as a single
3150 string. This is convenient for all cases except
3151 import a.b.c as d
3152 where we need to parse that string to extract the individual
3153 module names.
3154 XXX Perhaps change the representation to make this case simpler?
3155 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003156 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 for (i = 0; i < n; i++) {
3159 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3160 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003162 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3163 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 if (alias->asname) {
3167 r = compiler_import_as(c, alias->name, alias->asname);
3168 if (!r)
3169 return r;
3170 }
3171 else {
3172 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 Py_ssize_t dot = PyUnicode_FindChar(
3174 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003175 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003176 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003177 if (tmp == NULL)
3178 return 0;
3179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003181 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 Py_DECREF(tmp);
3183 }
3184 if (!r)
3185 return r;
3186 }
3187 }
3188 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189}
3190
3191static int
3192compiler_from_import(struct compiler *c, stmt_ty s)
3193{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003194 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003195 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 if (!empty_string) {
3199 empty_string = PyUnicode_FromString("");
3200 if (!empty_string)
3201 return 0;
3202 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003204 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003205
3206 names = PyTuple_New(n);
3207 if (!names)
3208 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* build up the names */
3211 for (i = 0; i < n; i++) {
3212 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3213 Py_INCREF(alias->name);
3214 PyTuple_SET_ITEM(names, i, alias->name);
3215 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003218 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 Py_DECREF(names);
3220 return compiler_error(c, "from __future__ imports must occur "
3221 "at the beginning of the file");
3222 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003223 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 if (s->v.ImportFrom.module) {
3226 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3227 }
3228 else {
3229 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3230 }
3231 for (i = 0; i < n; i++) {
3232 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3233 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003235 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 assert(n == 1);
3237 ADDOP(c, IMPORT_STAR);
3238 return 1;
3239 }
3240
3241 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3242 store_name = alias->name;
3243 if (alias->asname)
3244 store_name = alias->asname;
3245
3246 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 return 0;
3248 }
3249 }
3250 /* remove imported module */
3251 ADDOP(c, POP_TOP);
3252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253}
3254
3255static int
3256compiler_assert(struct compiler *c, stmt_ty s)
3257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
Georg Brandl8334fd92010-12-04 10:26:46 +00003260 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003263 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3264 {
3265 if (!compiler_warn(c, "assertion is always true, "
3266 "perhaps remove parentheses?"))
3267 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003268 return 0;
3269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 end = compiler_new_block(c);
3272 if (end == NULL)
3273 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003274 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3275 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003276 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (s->v.Assert.msg) {
3278 VISIT(c, expr, s->v.Assert.msg);
3279 ADDOP_I(c, CALL_FUNCTION, 1);
3280 }
3281 ADDOP_I(c, RAISE_VARARGS, 1);
3282 compiler_use_next_block(c, end);
3283 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284}
3285
3286static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003287compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3288{
3289 if (c->c_interactive && c->c_nestlevel <= 1) {
3290 VISIT(c, expr, value);
3291 ADDOP(c, PRINT_EXPR);
3292 return 1;
3293 }
3294
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003295 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003296 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003297 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003298 }
3299
3300 VISIT(c, expr, value);
3301 ADDOP(c, POP_TOP);
3302 return 1;
3303}
3304
3305static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306compiler_visit_stmt(struct compiler *c, stmt_ty s)
3307{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003308 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 /* Always assign a lineno to the next instruction for a stmt. */
3311 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003312 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 switch (s->kind) {
3316 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003317 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 case ClassDef_kind:
3319 return compiler_class(c, s);
3320 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003321 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 case Delete_kind:
3323 VISIT_SEQ(c, expr, s->v.Delete.targets)
3324 break;
3325 case Assign_kind:
3326 n = asdl_seq_LEN(s->v.Assign.targets);
3327 VISIT(c, expr, s->v.Assign.value);
3328 for (i = 0; i < n; i++) {
3329 if (i < n - 1)
3330 ADDOP(c, DUP_TOP);
3331 VISIT(c, expr,
3332 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3333 }
3334 break;
3335 case AugAssign_kind:
3336 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003337 case AnnAssign_kind:
3338 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 case For_kind:
3340 return compiler_for(c, s);
3341 case While_kind:
3342 return compiler_while(c, s);
3343 case If_kind:
3344 return compiler_if(c, s);
3345 case Raise_kind:
3346 n = 0;
3347 if (s->v.Raise.exc) {
3348 VISIT(c, expr, s->v.Raise.exc);
3349 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003350 if (s->v.Raise.cause) {
3351 VISIT(c, expr, s->v.Raise.cause);
3352 n++;
3353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003355 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003357 case Try_kind:
3358 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 case Assert_kind:
3360 return compiler_assert(c, s);
3361 case Import_kind:
3362 return compiler_import(c, s);
3363 case ImportFrom_kind:
3364 return compiler_from_import(c, s);
3365 case Global_kind:
3366 case Nonlocal_kind:
3367 break;
3368 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003369 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 case Pass_kind:
3371 break;
3372 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003373 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case Continue_kind:
3375 return compiler_continue(c);
3376 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003377 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003378 case AsyncFunctionDef_kind:
3379 return compiler_function(c, s, 1);
3380 case AsyncWith_kind:
3381 return compiler_async_with(c, s, 0);
3382 case AsyncFor_kind:
3383 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 }
Yury Selivanov75445082015-05-11 22:57:16 -04003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387}
3388
3389static int
3390unaryop(unaryop_ty op)
3391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 switch (op) {
3393 case Invert:
3394 return UNARY_INVERT;
3395 case Not:
3396 return UNARY_NOT;
3397 case UAdd:
3398 return UNARY_POSITIVE;
3399 case USub:
3400 return UNARY_NEGATIVE;
3401 default:
3402 PyErr_Format(PyExc_SystemError,
3403 "unary op %d should not be possible", op);
3404 return 0;
3405 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406}
3407
3408static int
3409binop(struct compiler *c, operator_ty op)
3410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 switch (op) {
3412 case Add:
3413 return BINARY_ADD;
3414 case Sub:
3415 return BINARY_SUBTRACT;
3416 case Mult:
3417 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003418 case MatMult:
3419 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 case Div:
3421 return BINARY_TRUE_DIVIDE;
3422 case Mod:
3423 return BINARY_MODULO;
3424 case Pow:
3425 return BINARY_POWER;
3426 case LShift:
3427 return BINARY_LSHIFT;
3428 case RShift:
3429 return BINARY_RSHIFT;
3430 case BitOr:
3431 return BINARY_OR;
3432 case BitXor:
3433 return BINARY_XOR;
3434 case BitAnd:
3435 return BINARY_AND;
3436 case FloorDiv:
3437 return BINARY_FLOOR_DIVIDE;
3438 default:
3439 PyErr_Format(PyExc_SystemError,
3440 "binary op %d should not be possible", op);
3441 return 0;
3442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446inplace_binop(struct compiler *c, operator_ty op)
3447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 switch (op) {
3449 case Add:
3450 return INPLACE_ADD;
3451 case Sub:
3452 return INPLACE_SUBTRACT;
3453 case Mult:
3454 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003455 case MatMult:
3456 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 case Div:
3458 return INPLACE_TRUE_DIVIDE;
3459 case Mod:
3460 return INPLACE_MODULO;
3461 case Pow:
3462 return INPLACE_POWER;
3463 case LShift:
3464 return INPLACE_LSHIFT;
3465 case RShift:
3466 return INPLACE_RSHIFT;
3467 case BitOr:
3468 return INPLACE_OR;
3469 case BitXor:
3470 return INPLACE_XOR;
3471 case BitAnd:
3472 return INPLACE_AND;
3473 case FloorDiv:
3474 return INPLACE_FLOOR_DIVIDE;
3475 default:
3476 PyErr_Format(PyExc_SystemError,
3477 "inplace binary op %d should not be possible", op);
3478 return 0;
3479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480}
3481
3482static int
3483compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3484{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003485 int op, scope;
3486 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 PyObject *dict = c->u->u_names;
3490 PyObject *mangled;
3491 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003493 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3494 !_PyUnicode_EqualToASCIIString(name, "True") &&
3495 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003496
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003497 mangled = _Py_Mangle(c->u->u_private, name);
3498 if (!mangled)
3499 return 0;
3500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 op = 0;
3502 optype = OP_NAME;
3503 scope = PyST_GetScope(c->u->u_ste, mangled);
3504 switch (scope) {
3505 case FREE:
3506 dict = c->u->u_freevars;
3507 optype = OP_DEREF;
3508 break;
3509 case CELL:
3510 dict = c->u->u_cellvars;
3511 optype = OP_DEREF;
3512 break;
3513 case LOCAL:
3514 if (c->u->u_ste->ste_type == FunctionBlock)
3515 optype = OP_FAST;
3516 break;
3517 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003518 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 optype = OP_GLOBAL;
3520 break;
3521 case GLOBAL_EXPLICIT:
3522 optype = OP_GLOBAL;
3523 break;
3524 default:
3525 /* scope can be 0 */
3526 break;
3527 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003530 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 switch (optype) {
3533 case OP_DEREF:
3534 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003535 case Load:
3536 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3537 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003538 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003539 op = STORE_DEREF;
3540 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 case AugLoad:
3542 case AugStore:
3543 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003544 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 case Param:
3546 default:
3547 PyErr_SetString(PyExc_SystemError,
3548 "param invalid for deref variable");
3549 return 0;
3550 }
3551 break;
3552 case OP_FAST:
3553 switch (ctx) {
3554 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003555 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003556 op = STORE_FAST;
3557 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 case Del: op = DELETE_FAST; break;
3559 case AugLoad:
3560 case AugStore:
3561 break;
3562 case Param:
3563 default:
3564 PyErr_SetString(PyExc_SystemError,
3565 "param invalid for local variable");
3566 return 0;
3567 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003568 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 return 1;
3570 case OP_GLOBAL:
3571 switch (ctx) {
3572 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003573 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003574 op = STORE_GLOBAL;
3575 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 case Del: op = DELETE_GLOBAL; break;
3577 case AugLoad:
3578 case AugStore:
3579 break;
3580 case Param:
3581 default:
3582 PyErr_SetString(PyExc_SystemError,
3583 "param invalid for global variable");
3584 return 0;
3585 }
3586 break;
3587 case OP_NAME:
3588 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003589 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003590 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003591 op = STORE_NAME;
3592 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 case Del: op = DELETE_NAME; break;
3594 case AugLoad:
3595 case AugStore:
3596 break;
3597 case Param:
3598 default:
3599 PyErr_SetString(PyExc_SystemError,
3600 "param invalid for name variable");
3601 return 0;
3602 }
3603 break;
3604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 assert(op);
3607 arg = compiler_add_o(c, dict, mangled);
3608 Py_DECREF(mangled);
3609 if (arg < 0)
3610 return 0;
3611 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
3614static int
3615compiler_boolop(struct compiler *c, expr_ty e)
3616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003618 int jumpi;
3619 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 assert(e->kind == BoolOp_kind);
3623 if (e->v.BoolOp.op == And)
3624 jumpi = JUMP_IF_FALSE_OR_POP;
3625 else
3626 jumpi = JUMP_IF_TRUE_OR_POP;
3627 end = compiler_new_block(c);
3628 if (end == NULL)
3629 return 0;
3630 s = e->v.BoolOp.values;
3631 n = asdl_seq_LEN(s) - 1;
3632 assert(n >= 0);
3633 for (i = 0; i < n; ++i) {
3634 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3635 ADDOP_JABS(c, jumpi, end);
3636 }
3637 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3638 compiler_use_next_block(c, end);
3639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640}
3641
3642static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003643starunpack_helper(struct compiler *c, asdl_seq *elts,
3644 int single_op, int inner_op, int outer_op)
3645{
3646 Py_ssize_t n = asdl_seq_LEN(elts);
3647 Py_ssize_t i, nsubitems = 0, nseen = 0;
3648 for (i = 0; i < n; i++) {
3649 expr_ty elt = asdl_seq_GET(elts, i);
3650 if (elt->kind == Starred_kind) {
3651 if (nseen) {
3652 ADDOP_I(c, inner_op, nseen);
3653 nseen = 0;
3654 nsubitems++;
3655 }
3656 VISIT(c, expr, elt->v.Starred.value);
3657 nsubitems++;
3658 }
3659 else {
3660 VISIT(c, expr, elt);
3661 nseen++;
3662 }
3663 }
3664 if (nsubitems) {
3665 if (nseen) {
3666 ADDOP_I(c, inner_op, nseen);
3667 nsubitems++;
3668 }
3669 ADDOP_I(c, outer_op, nsubitems);
3670 }
3671 else
3672 ADDOP_I(c, single_op, nseen);
3673 return 1;
3674}
3675
3676static int
3677assignment_helper(struct compiler *c, asdl_seq *elts)
3678{
3679 Py_ssize_t n = asdl_seq_LEN(elts);
3680 Py_ssize_t i;
3681 int seen_star = 0;
3682 for (i = 0; i < n; i++) {
3683 expr_ty elt = asdl_seq_GET(elts, i);
3684 if (elt->kind == Starred_kind && !seen_star) {
3685 if ((i >= (1 << 8)) ||
3686 (n-i-1 >= (INT_MAX >> 8)))
3687 return compiler_error(c,
3688 "too many expressions in "
3689 "star-unpacking assignment");
3690 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3691 seen_star = 1;
3692 asdl_seq_SET(elts, i, elt->v.Starred.value);
3693 }
3694 else if (elt->kind == Starred_kind) {
3695 return compiler_error(c,
3696 "two starred expressions in assignment");
3697 }
3698 }
3699 if (!seen_star) {
3700 ADDOP_I(c, UNPACK_SEQUENCE, n);
3701 }
3702 VISIT_SEQ(c, expr, elts);
3703 return 1;
3704}
3705
3706static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707compiler_list(struct compiler *c, expr_ty e)
3708{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003709 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003710 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003711 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003713 else if (e->v.List.ctx == Load) {
3714 return starunpack_helper(c, elts,
3715 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 else
3718 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720}
3721
3722static int
3723compiler_tuple(struct compiler *c, expr_ty e)
3724{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003726 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 return assignment_helper(c, elts);
3728 }
3729 else if (e->v.Tuple.ctx == Load) {
3730 return starunpack_helper(c, elts,
3731 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3732 }
3733 else
3734 VISIT_SEQ(c, expr, elts);
3735 return 1;
3736}
3737
3738static int
3739compiler_set(struct compiler *c, expr_ty e)
3740{
3741 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3742 BUILD_SET, BUILD_SET_UNPACK);
3743}
3744
3745static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003746are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3747{
3748 Py_ssize_t i;
3749 for (i = begin; i < end; i++) {
3750 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003751 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003752 return 0;
3753 }
3754 return 1;
3755}
3756
3757static int
3758compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3759{
3760 Py_ssize_t i, n = end - begin;
3761 PyObject *keys, *key;
3762 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3763 for (i = begin; i < end; i++) {
3764 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3765 }
3766 keys = PyTuple_New(n);
3767 if (keys == NULL) {
3768 return 0;
3769 }
3770 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003771 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003772 Py_INCREF(key);
3773 PyTuple_SET_ITEM(keys, i - begin, key);
3774 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003775 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003776 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3777 }
3778 else {
3779 for (i = begin; i < end; i++) {
3780 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3781 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3782 }
3783 ADDOP_I(c, BUILD_MAP, n);
3784 }
3785 return 1;
3786}
3787
3788static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789compiler_dict(struct compiler *c, expr_ty e)
3790{
Victor Stinner976bb402016-03-23 11:36:19 +01003791 Py_ssize_t i, n, elements;
3792 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793 int is_unpacking = 0;
3794 n = asdl_seq_LEN(e->v.Dict.values);
3795 containers = 0;
3796 elements = 0;
3797 for (i = 0; i < n; i++) {
3798 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3799 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003800 if (!compiler_subdict(c, e, i - elements, i))
3801 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003802 containers++;
3803 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 if (is_unpacking) {
3806 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3807 containers++;
3808 }
3809 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 }
3812 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003813 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003814 if (!compiler_subdict(c, e, n - elements, n))
3815 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003816 containers++;
3817 }
3818 /* If there is more than one dict, they need to be merged into a new
3819 * dict. If there is one dict and it's an unpacking, then it needs
3820 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003821 if (containers > 1 || is_unpacking) {
3822 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
3824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825}
3826
3827static int
3828compiler_compare(struct compiler *c, expr_ty e)
3829{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003830 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003832 if (!check_compare(c, e)) {
3833 return 0;
3834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003836 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3837 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3838 if (n == 0) {
3839 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3840 ADDOP_I(c, COMPARE_OP,
3841 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3842 }
3843 else {
3844 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 if (cleanup == NULL)
3846 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003847 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 VISIT(c, expr,
3849 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003850 ADDOP(c, DUP_TOP);
3851 ADDOP(c, ROT_THREE);
3852 ADDOP_I(c, COMPARE_OP,
3853 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3854 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3855 NEXT_BLOCK(c);
3856 }
3857 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3858 ADDOP_I(c, COMPARE_OP,
3859 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 basicblock *end = compiler_new_block(c);
3861 if (end == NULL)
3862 return 0;
3863 ADDOP_JREL(c, JUMP_FORWARD, end);
3864 compiler_use_next_block(c, cleanup);
3865 ADDOP(c, ROT_TWO);
3866 ADDOP(c, POP_TOP);
3867 compiler_use_next_block(c, end);
3868 }
3869 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870}
3871
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003872static PyTypeObject *
3873infer_type(expr_ty e)
3874{
3875 switch (e->kind) {
3876 case Tuple_kind:
3877 return &PyTuple_Type;
3878 case List_kind:
3879 case ListComp_kind:
3880 return &PyList_Type;
3881 case Dict_kind:
3882 case DictComp_kind:
3883 return &PyDict_Type;
3884 case Set_kind:
3885 case SetComp_kind:
3886 return &PySet_Type;
3887 case GeneratorExp_kind:
3888 return &PyGen_Type;
3889 case Lambda_kind:
3890 return &PyFunction_Type;
3891 case JoinedStr_kind:
3892 case FormattedValue_kind:
3893 return &PyUnicode_Type;
3894 case Constant_kind:
3895 return e->v.Constant.value->ob_type;
3896 default:
3897 return NULL;
3898 }
3899}
3900
3901static int
3902check_caller(struct compiler *c, expr_ty e)
3903{
3904 switch (e->kind) {
3905 case Constant_kind:
3906 case Tuple_kind:
3907 case List_kind:
3908 case ListComp_kind:
3909 case Dict_kind:
3910 case DictComp_kind:
3911 case Set_kind:
3912 case SetComp_kind:
3913 case GeneratorExp_kind:
3914 case JoinedStr_kind:
3915 case FormattedValue_kind:
3916 return compiler_warn(c, "'%.200s' object is not callable; "
3917 "perhaps you missed a comma?",
3918 infer_type(e)->tp_name);
3919 default:
3920 return 1;
3921 }
3922}
3923
3924static int
3925check_subscripter(struct compiler *c, expr_ty e)
3926{
3927 PyObject *v;
3928
3929 switch (e->kind) {
3930 case Constant_kind:
3931 v = e->v.Constant.value;
3932 if (!(v == Py_None || v == Py_Ellipsis ||
3933 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3934 PyAnySet_Check(v)))
3935 {
3936 return 1;
3937 }
3938 /* fall through */
3939 case Set_kind:
3940 case SetComp_kind:
3941 case GeneratorExp_kind:
3942 case Lambda_kind:
3943 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3944 "perhaps you missed a comma?",
3945 infer_type(e)->tp_name);
3946 default:
3947 return 1;
3948 }
3949}
3950
3951static int
3952check_index(struct compiler *c, expr_ty e, slice_ty s)
3953{
3954 PyObject *v;
3955
3956 if (s->kind != Index_kind) {
3957 return 1;
3958 }
3959 PyTypeObject *index_type = infer_type(s->v.Index.value);
3960 if (index_type == NULL
3961 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3962 || index_type == &PySlice_Type) {
3963 return 1;
3964 }
3965
3966 switch (e->kind) {
3967 case Constant_kind:
3968 v = e->v.Constant.value;
3969 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3970 return 1;
3971 }
3972 /* fall through */
3973 case Tuple_kind:
3974 case List_kind:
3975 case ListComp_kind:
3976 case JoinedStr_kind:
3977 case FormattedValue_kind:
3978 return compiler_warn(c, "%.200s indices must be integers or slices, "
3979 "not %.200s; "
3980 "perhaps you missed a comma?",
3981 infer_type(e)->tp_name,
3982 index_type->tp_name);
3983 default:
3984 return 1;
3985 }
3986}
3987
Zackery Spytz97f5de02019-03-22 01:30:32 -06003988// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003989static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003990maybe_optimize_method_call(struct compiler *c, expr_ty e)
3991{
3992 Py_ssize_t argsl, i;
3993 expr_ty meth = e->v.Call.func;
3994 asdl_seq *args = e->v.Call.args;
3995
3996 /* Check that the call node is an attribute access, and that
3997 the call doesn't have keyword parameters. */
3998 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3999 asdl_seq_LEN(e->v.Call.keywords))
4000 return -1;
4001
4002 /* Check that there are no *varargs types of arguments. */
4003 argsl = asdl_seq_LEN(args);
4004 for (i = 0; i < argsl; i++) {
4005 expr_ty elt = asdl_seq_GET(args, i);
4006 if (elt->kind == Starred_kind) {
4007 return -1;
4008 }
4009 }
4010
4011 /* Alright, we can optimize the code. */
4012 VISIT(c, expr, meth->v.Attribute.value);
4013 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4014 VISIT_SEQ(c, expr, e->v.Call.args);
4015 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4016 return 1;
4017}
4018
4019static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020compiler_call(struct compiler *c, expr_ty e)
4021{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004022 int ret = maybe_optimize_method_call(c, e);
4023 if (ret >= 0) {
4024 return ret;
4025 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004026 if (!check_caller(c, e->v.Call.func)) {
4027 return 0;
4028 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 VISIT(c, expr, e->v.Call.func);
4030 return compiler_call_helper(c, 0,
4031 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004032 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004033}
4034
Eric V. Smith235a6f02015-09-19 14:51:32 -04004035static int
4036compiler_joined_str(struct compiler *c, expr_ty e)
4037{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004038 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004039 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4040 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004041 return 1;
4042}
4043
Eric V. Smitha78c7952015-11-03 12:45:05 -05004044/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004045static int
4046compiler_formatted_value(struct compiler *c, expr_ty e)
4047{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004048 /* Our oparg encodes 2 pieces of information: the conversion
4049 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004050
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004051 Convert the conversion char to 3 bits:
4052 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004053 !s : 001 0x1 FVC_STR
4054 !r : 010 0x2 FVC_REPR
4055 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004056
Eric V. Smitha78c7952015-11-03 12:45:05 -05004057 next bit is whether or not we have a format spec:
4058 yes : 100 0x4
4059 no : 000 0x0
4060 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004061
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004062 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004063 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004064
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004065 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004066 VISIT(c, expr, e->v.FormattedValue.value);
4067
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004068 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004069 case 's': oparg = FVC_STR; break;
4070 case 'r': oparg = FVC_REPR; break;
4071 case 'a': oparg = FVC_ASCII; break;
4072 case -1: oparg = FVC_NONE; break;
4073 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004074 PyErr_Format(PyExc_SystemError,
4075 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004076 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004077 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004078 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004079 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004080 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004081 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004082 }
4083
Eric V. Smitha78c7952015-11-03 12:45:05 -05004084 /* And push our opcode and oparg */
4085 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004086
Eric V. Smith235a6f02015-09-19 14:51:32 -04004087 return 1;
4088}
4089
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004090static int
4091compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4092{
4093 Py_ssize_t i, n = end - begin;
4094 keyword_ty kw;
4095 PyObject *keys, *key;
4096 assert(n > 0);
4097 if (n > 1) {
4098 for (i = begin; i < end; i++) {
4099 kw = asdl_seq_GET(keywords, i);
4100 VISIT(c, expr, kw->value);
4101 }
4102 keys = PyTuple_New(n);
4103 if (keys == NULL) {
4104 return 0;
4105 }
4106 for (i = begin; i < end; i++) {
4107 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4108 Py_INCREF(key);
4109 PyTuple_SET_ITEM(keys, i - begin, key);
4110 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004111 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004112 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4113 }
4114 else {
4115 /* a for loop only executes once */
4116 for (i = begin; i < end; i++) {
4117 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004118 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004119 VISIT(c, expr, kw->value);
4120 }
4121 ADDOP_I(c, BUILD_MAP, n);
4122 }
4123 return 1;
4124}
4125
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004126/* shared code between compiler_call and compiler_class */
4127static int
4128compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004129 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004130 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004131 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004132{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004133 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004134 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004135
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004136 /* the number of tuples and dictionaries on the stack */
4137 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4138
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004139 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004140 nkwelts = asdl_seq_LEN(keywords);
4141
4142 for (i = 0; i < nkwelts; i++) {
4143 keyword_ty kw = asdl_seq_GET(keywords, i);
4144 if (kw->arg == NULL) {
4145 mustdictunpack = 1;
4146 break;
4147 }
4148 }
4149
4150 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004151 for (i = 0; i < nelts; i++) {
4152 expr_ty elt = asdl_seq_GET(args, i);
4153 if (elt->kind == Starred_kind) {
4154 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004155 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004156 if (nseen) {
4157 ADDOP_I(c, BUILD_TUPLE, nseen);
4158 nseen = 0;
4159 nsubargs++;
4160 }
4161 VISIT(c, expr, elt->v.Starred.value);
4162 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004163 }
4164 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004165 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004166 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004169
4170 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004171 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004172 if (nseen) {
4173 /* Pack up any trailing positional arguments. */
4174 ADDOP_I(c, BUILD_TUPLE, nseen);
4175 nsubargs++;
4176 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004177 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004178 /* If we ended up with more than one stararg, we need
4179 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004180 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004181 }
4182 else if (nsubargs == 0) {
4183 ADDOP_I(c, BUILD_TUPLE, 0);
4184 }
4185 nseen = 0; /* the number of keyword arguments on the stack following */
4186 for (i = 0; i < nkwelts; i++) {
4187 keyword_ty kw = asdl_seq_GET(keywords, i);
4188 if (kw->arg == NULL) {
4189 /* A keyword argument unpacking. */
4190 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004191 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4192 return 0;
4193 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004194 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004195 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004196 VISIT(c, expr, kw->value);
4197 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004198 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004199 else {
4200 nseen++;
4201 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004202 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004203 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004204 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004205 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004206 return 0;
4207 nsubkwargs++;
4208 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004209 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004210 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004211 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004212 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004213 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4214 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004216 else if (nkwelts) {
4217 PyObject *names;
4218 VISIT_SEQ(c, keyword, keywords);
4219 names = PyTuple_New(nkwelts);
4220 if (names == NULL) {
4221 return 0;
4222 }
4223 for (i = 0; i < nkwelts; i++) {
4224 keyword_ty kw = asdl_seq_GET(keywords, i);
4225 Py_INCREF(kw->arg);
4226 PyTuple_SET_ITEM(names, i, kw->arg);
4227 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004228 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4230 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004232 else {
4233 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4234 return 1;
4235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236}
4237
Nick Coghlan650f0d02007-04-15 12:05:43 +00004238
4239/* List and set comprehensions and generator expressions work by creating a
4240 nested function to perform the actual iteration. This means that the
4241 iteration variables don't leak into the current scope.
4242 The defined function is called immediately following its definition, with the
4243 result of that call being the result of the expression.
4244 The LC/SC version returns the populated container, while the GE version is
4245 flagged in symtable.c as a generator, so it returns the generator object
4246 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004247
4248 Possible cleanups:
4249 - iterate over the generator sequence instead of using recursion
4250*/
4251
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004253static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254compiler_comprehension_generator(struct compiler *c,
4255 asdl_seq *generators, int gen_index,
4256 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004258 comprehension_ty gen;
4259 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4260 if (gen->is_async) {
4261 return compiler_async_comprehension_generator(
4262 c, generators, gen_index, elt, val, type);
4263 } else {
4264 return compiler_sync_comprehension_generator(
4265 c, generators, gen_index, elt, val, type);
4266 }
4267}
4268
4269static int
4270compiler_sync_comprehension_generator(struct compiler *c,
4271 asdl_seq *generators, int gen_index,
4272 expr_ty elt, expr_ty val, int type)
4273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 /* generate code for the iterator, then each of the ifs,
4275 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 comprehension_ty gen;
4278 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004279 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 start = compiler_new_block(c);
4282 skip = compiler_new_block(c);
4283 if_cleanup = compiler_new_block(c);
4284 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4287 anchor == NULL)
4288 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (gen_index == 0) {
4293 /* Receive outermost iter as an implicit argument */
4294 c->u->u_argcount = 1;
4295 ADDOP_I(c, LOAD_FAST, 0);
4296 }
4297 else {
4298 /* Sub-iter - calculate on the fly */
4299 VISIT(c, expr, gen->iter);
4300 ADDOP(c, GET_ITER);
4301 }
4302 compiler_use_next_block(c, start);
4303 ADDOP_JREL(c, FOR_ITER, anchor);
4304 NEXT_BLOCK(c);
4305 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 /* XXX this needs to be cleaned up...a lot! */
4308 n = asdl_seq_LEN(gen->ifs);
4309 for (i = 0; i < n; i++) {
4310 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004311 if (!compiler_jump_if(c, e, if_cleanup, 0))
4312 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 NEXT_BLOCK(c);
4314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 if (++gen_index < asdl_seq_LEN(generators))
4317 if (!compiler_comprehension_generator(c,
4318 generators, gen_index,
4319 elt, val, type))
4320 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 /* only append after the last for generator */
4323 if (gen_index >= asdl_seq_LEN(generators)) {
4324 /* comprehension specific code */
4325 switch (type) {
4326 case COMP_GENEXP:
4327 VISIT(c, expr, elt);
4328 ADDOP(c, YIELD_VALUE);
4329 ADDOP(c, POP_TOP);
4330 break;
4331 case COMP_LISTCOMP:
4332 VISIT(c, expr, elt);
4333 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4334 break;
4335 case COMP_SETCOMP:
4336 VISIT(c, expr, elt);
4337 ADDOP_I(c, SET_ADD, gen_index + 1);
4338 break;
4339 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004340 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004343 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 ADDOP_I(c, MAP_ADD, gen_index + 1);
4345 break;
4346 default:
4347 return 0;
4348 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 compiler_use_next_block(c, skip);
4351 }
4352 compiler_use_next_block(c, if_cleanup);
4353 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4354 compiler_use_next_block(c, anchor);
4355
4356 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004357}
4358
4359static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004360compiler_async_comprehension_generator(struct compiler *c,
4361 asdl_seq *generators, int gen_index,
4362 expr_ty elt, expr_ty val, int type)
4363{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004364 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004365 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004366 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004367 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004369 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004370
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004371 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 return 0;
4373 }
4374
4375 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4376
4377 if (gen_index == 0) {
4378 /* Receive outermost iter as an implicit argument */
4379 c->u->u_argcount = 1;
4380 ADDOP_I(c, LOAD_FAST, 0);
4381 }
4382 else {
4383 /* Sub-iter - calculate on the fly */
4384 VISIT(c, expr, gen->iter);
4385 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004386 }
4387
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004388 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004389
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004390 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004391 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004392 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004393 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004394 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004395 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396
4397 n = asdl_seq_LEN(gen->ifs);
4398 for (i = 0; i < n; i++) {
4399 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004400 if (!compiler_jump_if(c, e, if_cleanup, 0))
4401 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004402 NEXT_BLOCK(c);
4403 }
4404
4405 if (++gen_index < asdl_seq_LEN(generators))
4406 if (!compiler_comprehension_generator(c,
4407 generators, gen_index,
4408 elt, val, type))
4409 return 0;
4410
4411 /* only append after the last for generator */
4412 if (gen_index >= asdl_seq_LEN(generators)) {
4413 /* comprehension specific code */
4414 switch (type) {
4415 case COMP_GENEXP:
4416 VISIT(c, expr, elt);
4417 ADDOP(c, YIELD_VALUE);
4418 ADDOP(c, POP_TOP);
4419 break;
4420 case COMP_LISTCOMP:
4421 VISIT(c, expr, elt);
4422 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4423 break;
4424 case COMP_SETCOMP:
4425 VISIT(c, expr, elt);
4426 ADDOP_I(c, SET_ADD, gen_index + 1);
4427 break;
4428 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004429 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004431 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004432 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004433 ADDOP_I(c, MAP_ADD, gen_index + 1);
4434 break;
4435 default:
4436 return 0;
4437 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004438 }
4439 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004440 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4441
4442 compiler_use_next_block(c, except);
4443 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004444
4445 return 1;
4446}
4447
4448static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004449compiler_comprehension(struct compiler *c, expr_ty e, int type,
4450 identifier name, asdl_seq *generators, expr_ty elt,
4451 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004454 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004455 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004456 int is_async_function = c->u->u_ste->ste_coroutine;
4457 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004458
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004459 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004460
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004461 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4462 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004463 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004465 }
4466
4467 is_async_generator = c->u->u_ste->ste_coroutine;
4468
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004469 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004470 compiler_error(c, "asynchronous comprehension outside of "
4471 "an asynchronous function");
4472 goto error_in_scope;
4473 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 if (type != COMP_GENEXP) {
4476 int op;
4477 switch (type) {
4478 case COMP_LISTCOMP:
4479 op = BUILD_LIST;
4480 break;
4481 case COMP_SETCOMP:
4482 op = BUILD_SET;
4483 break;
4484 case COMP_DICTCOMP:
4485 op = BUILD_MAP;
4486 break;
4487 default:
4488 PyErr_Format(PyExc_SystemError,
4489 "unknown comprehension type %d", type);
4490 goto error_in_scope;
4491 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 ADDOP_I(c, op, 0);
4494 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (!compiler_comprehension_generator(c, generators, 0, elt,
4497 val, type))
4498 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (type != COMP_GENEXP) {
4501 ADDOP(c, RETURN_VALUE);
4502 }
4503
4504 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004505 qualname = c->u->u_qualname;
4506 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004508 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 goto error;
4510
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004511 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004513 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 Py_DECREF(co);
4515
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 VISIT(c, expr, outermost->iter);
4517
4518 if (outermost->is_async) {
4519 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 } else {
4521 ADDOP(c, GET_ITER);
4522 }
4523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525
4526 if (is_async_generator && type != COMP_GENEXP) {
4527 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004528 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 ADDOP(c, YIELD_FROM);
4530 }
4531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004533error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004535error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004536 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 Py_XDECREF(co);
4538 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004539}
4540
4541static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542compiler_genexp(struct compiler *c, expr_ty e)
4543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 static identifier name;
4545 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004546 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 if (!name)
4548 return 0;
4549 }
4550 assert(e->kind == GeneratorExp_kind);
4551 return compiler_comprehension(c, e, COMP_GENEXP, name,
4552 e->v.GeneratorExp.generators,
4553 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004554}
4555
4556static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004557compiler_listcomp(struct compiler *c, expr_ty e)
4558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 static identifier name;
4560 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004561 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 if (!name)
4563 return 0;
4564 }
4565 assert(e->kind == ListComp_kind);
4566 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4567 e->v.ListComp.generators,
4568 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004569}
4570
4571static int
4572compiler_setcomp(struct compiler *c, expr_ty e)
4573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 static identifier name;
4575 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004576 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (!name)
4578 return 0;
4579 }
4580 assert(e->kind == SetComp_kind);
4581 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4582 e->v.SetComp.generators,
4583 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004584}
4585
4586
4587static int
4588compiler_dictcomp(struct compiler *c, expr_ty e)
4589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 static identifier name;
4591 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004592 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 if (!name)
4594 return 0;
4595 }
4596 assert(e->kind == DictComp_kind);
4597 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4598 e->v.DictComp.generators,
4599 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004600}
4601
4602
4603static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004604compiler_visit_keyword(struct compiler *c, keyword_ty k)
4605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 VISIT(c, expr, k->value);
4607 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004608}
4609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004611 whether they are true or false.
4612
4613 Return values: 1 for true, 0 for false, -1 for non-constant.
4614 */
4615
4616static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004617expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004618{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004619 if (e->kind == Constant_kind) {
4620 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004621 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004622 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004623}
4624
Yury Selivanov75445082015-05-11 22:57:16 -04004625
4626/*
4627 Implements the async with statement.
4628
4629 The semantics outlined in that PEP are as follows:
4630
4631 async with EXPR as VAR:
4632 BLOCK
4633
4634 It is implemented roughly as:
4635
4636 context = EXPR
4637 exit = context.__aexit__ # not calling it
4638 value = await context.__aenter__()
4639 try:
4640 VAR = value # if VAR present in the syntax
4641 BLOCK
4642 finally:
4643 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004644 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004645 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004646 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004647 if not (await exit(*exc)):
4648 raise
4649 */
4650static int
4651compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4652{
4653 basicblock *block, *finally;
4654 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4655
4656 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004657 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4658 c->u->u_ste->ste_coroutine = 1;
4659 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004660 return compiler_error(c, "'async with' outside async function");
4661 }
Yury Selivanov75445082015-05-11 22:57:16 -04004662
4663 block = compiler_new_block(c);
4664 finally = compiler_new_block(c);
4665 if (!block || !finally)
4666 return 0;
4667
4668 /* Evaluate EXPR */
4669 VISIT(c, expr, item->context_expr);
4670
4671 ADDOP(c, BEFORE_ASYNC_WITH);
4672 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004673 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004674 ADDOP(c, YIELD_FROM);
4675
4676 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4677
4678 /* SETUP_ASYNC_WITH pushes a finally block. */
4679 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004680 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004681 return 0;
4682 }
4683
4684 if (item->optional_vars) {
4685 VISIT(c, expr, item->optional_vars);
4686 }
4687 else {
4688 /* Discard result from context.__aenter__() */
4689 ADDOP(c, POP_TOP);
4690 }
4691
4692 pos++;
4693 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4694 /* BLOCK code */
4695 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4696 else if (!compiler_async_with(c, s, pos))
4697 return 0;
4698
4699 /* End of try block; start the finally block */
4700 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004701 ADDOP(c, BEGIN_FINALLY);
4702 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004703
Yury Selivanov75445082015-05-11 22:57:16 -04004704 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004705 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004706 return 0;
4707
4708 /* Finally block starts; context.__exit__ is on the stack under
4709 the exception or return information. Just issue our magic
4710 opcode. */
4711 ADDOP(c, WITH_CLEANUP_START);
4712
4713 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004714 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004715 ADDOP(c, YIELD_FROM);
4716
4717 ADDOP(c, WITH_CLEANUP_FINISH);
4718
4719 /* Finally block ends. */
4720 ADDOP(c, END_FINALLY);
4721 compiler_pop_fblock(c, FINALLY_END, finally);
4722 return 1;
4723}
4724
4725
Guido van Rossumc2e20742006-02-27 22:32:47 +00004726/*
4727 Implements the with statement from PEP 343.
4728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004730
4731 with EXPR as VAR:
4732 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733
Guido van Rossumc2e20742006-02-27 22:32:47 +00004734 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735
Thomas Wouters477c8d52006-05-27 19:21:47 +00004736 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004737 exit = context.__exit__ # not calling it
4738 value = context.__enter__()
4739 try:
4740 VAR = value # if VAR present in the syntax
4741 BLOCK
4742 finally:
4743 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004744 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004745 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004746 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004747 exit(*exc)
4748 */
4749static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004750compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004751{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004752 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004753 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004754
4755 assert(s->kind == With_kind);
4756
Guido van Rossumc2e20742006-02-27 22:32:47 +00004757 block = compiler_new_block(c);
4758 finally = compiler_new_block(c);
4759 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004760 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004761
Thomas Wouters477c8d52006-05-27 19:21:47 +00004762 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004763 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004764 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004765
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004766 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004767 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004768 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004769 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004770 }
4771
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004772 if (item->optional_vars) {
4773 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004774 }
4775 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004777 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004778 }
4779
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004780 pos++;
4781 if (pos == asdl_seq_LEN(s->v.With.items))
4782 /* BLOCK code */
4783 VISIT_SEQ(c, stmt, s->v.With.body)
4784 else if (!compiler_with(c, s, pos))
4785 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004786
4787 /* End of try block; start the finally block */
4788 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004789 ADDOP(c, BEGIN_FINALLY);
4790 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004791
Guido van Rossumc2e20742006-02-27 22:32:47 +00004792 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004793 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004794 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004795
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004796 /* Finally block starts; context.__exit__ is on the stack under
4797 the exception or return information. Just issue our magic
4798 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004799 ADDOP(c, WITH_CLEANUP_START);
4800 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004801
4802 /* Finally block ends. */
4803 ADDOP(c, END_FINALLY);
4804 compiler_pop_fblock(c, FINALLY_END, finally);
4805 return 1;
4806}
4807
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004808static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004809compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004812 case NamedExpr_kind:
4813 VISIT(c, expr, e->v.NamedExpr.value);
4814 ADDOP(c, DUP_TOP);
4815 VISIT(c, expr, e->v.NamedExpr.target);
4816 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 case BoolOp_kind:
4818 return compiler_boolop(c, e);
4819 case BinOp_kind:
4820 VISIT(c, expr, e->v.BinOp.left);
4821 VISIT(c, expr, e->v.BinOp.right);
4822 ADDOP(c, binop(c, e->v.BinOp.op));
4823 break;
4824 case UnaryOp_kind:
4825 VISIT(c, expr, e->v.UnaryOp.operand);
4826 ADDOP(c, unaryop(e->v.UnaryOp.op));
4827 break;
4828 case Lambda_kind:
4829 return compiler_lambda(c, e);
4830 case IfExp_kind:
4831 return compiler_ifexp(c, e);
4832 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004833 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004835 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 case GeneratorExp_kind:
4837 return compiler_genexp(c, e);
4838 case ListComp_kind:
4839 return compiler_listcomp(c, e);
4840 case SetComp_kind:
4841 return compiler_setcomp(c, e);
4842 case DictComp_kind:
4843 return compiler_dictcomp(c, e);
4844 case Yield_kind:
4845 if (c->u->u_ste->ste_type != FunctionBlock)
4846 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004847 if (e->v.Yield.value) {
4848 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 }
4850 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004851 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004853 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004855 case YieldFrom_kind:
4856 if (c->u->u_ste->ste_type != FunctionBlock)
4857 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004858
4859 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4860 return compiler_error(c, "'yield from' inside async function");
4861
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004862 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004863 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004864 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004865 ADDOP(c, YIELD_FROM);
4866 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004867 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004868 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4869 if (c->u->u_ste->ste_type != FunctionBlock){
4870 return compiler_error(c, "'await' outside function");
4871 }
Yury Selivanov75445082015-05-11 22:57:16 -04004872
Victor Stinner331a6a52019-05-27 16:39:22 +02004873 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004874 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4875 return compiler_error(c, "'await' outside async function");
4876 }
4877 }
Yury Selivanov75445082015-05-11 22:57:16 -04004878
4879 VISIT(c, expr, e->v.Await.value);
4880 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004881 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004882 ADDOP(c, YIELD_FROM);
4883 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 case Compare_kind:
4885 return compiler_compare(c, e);
4886 case Call_kind:
4887 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004888 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004889 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004890 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004891 case JoinedStr_kind:
4892 return compiler_joined_str(c, e);
4893 case FormattedValue_kind:
4894 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 /* The following exprs can be assignment targets. */
4896 case Attribute_kind:
4897 if (e->v.Attribute.ctx != AugStore)
4898 VISIT(c, expr, e->v.Attribute.value);
4899 switch (e->v.Attribute.ctx) {
4900 case AugLoad:
4901 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004902 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 case Load:
4904 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4905 break;
4906 case AugStore:
4907 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004908 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 case Store:
4910 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4911 break;
4912 case Del:
4913 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4914 break;
4915 case Param:
4916 default:
4917 PyErr_SetString(PyExc_SystemError,
4918 "param invalid in attribute expression");
4919 return 0;
4920 }
4921 break;
4922 case Subscript_kind:
4923 switch (e->v.Subscript.ctx) {
4924 case AugLoad:
4925 VISIT(c, expr, e->v.Subscript.value);
4926 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4927 break;
4928 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004929 if (!check_subscripter(c, e->v.Subscript.value)) {
4930 return 0;
4931 }
4932 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4933 return 0;
4934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 VISIT(c, expr, e->v.Subscript.value);
4936 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4937 break;
4938 case AugStore:
4939 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4940 break;
4941 case Store:
4942 VISIT(c, expr, e->v.Subscript.value);
4943 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4944 break;
4945 case Del:
4946 VISIT(c, expr, e->v.Subscript.value);
4947 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4948 break;
4949 case Param:
4950 default:
4951 PyErr_SetString(PyExc_SystemError,
4952 "param invalid in subscript expression");
4953 return 0;
4954 }
4955 break;
4956 case Starred_kind:
4957 switch (e->v.Starred.ctx) {
4958 case Store:
4959 /* In all legitimate cases, the Starred node was already replaced
4960 * by compiler_list/compiler_tuple. XXX: is that okay? */
4961 return compiler_error(c,
4962 "starred assignment target must be in a list or tuple");
4963 default:
4964 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004965 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 case Name_kind:
4968 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4969 /* child nodes of List and Tuple will have expr_context set */
4970 case List_kind:
4971 return compiler_list(c, e);
4972 case Tuple_kind:
4973 return compiler_tuple(c, e);
4974 }
4975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004976}
4977
4978static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004979compiler_visit_expr(struct compiler *c, expr_ty e)
4980{
4981 /* If expr e has a different line number than the last expr/stmt,
4982 set a new line number for the next instruction.
4983 */
4984 int old_lineno = c->u->u_lineno;
4985 int old_col_offset = c->u->u_col_offset;
4986 if (e->lineno != c->u->u_lineno) {
4987 c->u->u_lineno = e->lineno;
4988 c->u->u_lineno_set = 0;
4989 }
4990 /* Updating the column offset is always harmless. */
4991 c->u->u_col_offset = e->col_offset;
4992
4993 int res = compiler_visit_expr1(c, e);
4994
4995 if (old_lineno != c->u->u_lineno) {
4996 c->u->u_lineno = old_lineno;
4997 c->u->u_lineno_set = 0;
4998 }
4999 c->u->u_col_offset = old_col_offset;
5000 return res;
5001}
5002
5003static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005004compiler_augassign(struct compiler *c, stmt_ty s)
5005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 expr_ty e = s->v.AugAssign.target;
5007 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 switch (e->kind) {
5012 case Attribute_kind:
5013 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005014 AugLoad, e->lineno, e->col_offset,
5015 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 if (auge == NULL)
5017 return 0;
5018 VISIT(c, expr, auge);
5019 VISIT(c, expr, s->v.AugAssign.value);
5020 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5021 auge->v.Attribute.ctx = AugStore;
5022 VISIT(c, expr, auge);
5023 break;
5024 case Subscript_kind:
5025 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005026 AugLoad, e->lineno, e->col_offset,
5027 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 if (auge == NULL)
5029 return 0;
5030 VISIT(c, expr, auge);
5031 VISIT(c, expr, s->v.AugAssign.value);
5032 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5033 auge->v.Subscript.ctx = AugStore;
5034 VISIT(c, expr, auge);
5035 break;
5036 case Name_kind:
5037 if (!compiler_nameop(c, e->v.Name.id, Load))
5038 return 0;
5039 VISIT(c, expr, s->v.AugAssign.value);
5040 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5041 return compiler_nameop(c, e->v.Name.id, Store);
5042 default:
5043 PyErr_Format(PyExc_SystemError,
5044 "invalid node type (%d) for augmented assignment",
5045 e->kind);
5046 return 0;
5047 }
5048 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005049}
5050
5051static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005052check_ann_expr(struct compiler *c, expr_ty e)
5053{
5054 VISIT(c, expr, e);
5055 ADDOP(c, POP_TOP);
5056 return 1;
5057}
5058
5059static int
5060check_annotation(struct compiler *c, stmt_ty s)
5061{
5062 /* Annotations are only evaluated in a module or class. */
5063 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5064 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5065 return check_ann_expr(c, s->v.AnnAssign.annotation);
5066 }
5067 return 1;
5068}
5069
5070static int
5071check_ann_slice(struct compiler *c, slice_ty sl)
5072{
5073 switch(sl->kind) {
5074 case Index_kind:
5075 return check_ann_expr(c, sl->v.Index.value);
5076 case Slice_kind:
5077 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5078 return 0;
5079 }
5080 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5081 return 0;
5082 }
5083 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5084 return 0;
5085 }
5086 break;
5087 default:
5088 PyErr_SetString(PyExc_SystemError,
5089 "unexpected slice kind");
5090 return 0;
5091 }
5092 return 1;
5093}
5094
5095static int
5096check_ann_subscr(struct compiler *c, slice_ty sl)
5097{
5098 /* We check that everything in a subscript is defined at runtime. */
5099 Py_ssize_t i, n;
5100
5101 switch (sl->kind) {
5102 case Index_kind:
5103 case Slice_kind:
5104 if (!check_ann_slice(c, sl)) {
5105 return 0;
5106 }
5107 break;
5108 case ExtSlice_kind:
5109 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5110 for (i = 0; i < n; i++) {
5111 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5112 switch (subsl->kind) {
5113 case Index_kind:
5114 case Slice_kind:
5115 if (!check_ann_slice(c, subsl)) {
5116 return 0;
5117 }
5118 break;
5119 case ExtSlice_kind:
5120 default:
5121 PyErr_SetString(PyExc_SystemError,
5122 "extended slice invalid in nested slice");
5123 return 0;
5124 }
5125 }
5126 break;
5127 default:
5128 PyErr_Format(PyExc_SystemError,
5129 "invalid subscript kind %d", sl->kind);
5130 return 0;
5131 }
5132 return 1;
5133}
5134
5135static int
5136compiler_annassign(struct compiler *c, stmt_ty s)
5137{
5138 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005139 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005140
5141 assert(s->kind == AnnAssign_kind);
5142
5143 /* We perform the actual assignment first. */
5144 if (s->v.AnnAssign.value) {
5145 VISIT(c, expr, s->v.AnnAssign.value);
5146 VISIT(c, expr, targ);
5147 }
5148 switch (targ->kind) {
5149 case Name_kind:
5150 /* If we have a simple name in a module or class, store annotation. */
5151 if (s->v.AnnAssign.simple &&
5152 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5153 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005154 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5155 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5156 }
5157 else {
5158 VISIT(c, expr, s->v.AnnAssign.annotation);
5159 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005160 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005161 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005162 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005163 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005164 }
5165 break;
5166 case Attribute_kind:
5167 if (!s->v.AnnAssign.value &&
5168 !check_ann_expr(c, targ->v.Attribute.value)) {
5169 return 0;
5170 }
5171 break;
5172 case Subscript_kind:
5173 if (!s->v.AnnAssign.value &&
5174 (!check_ann_expr(c, targ->v.Subscript.value) ||
5175 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5176 return 0;
5177 }
5178 break;
5179 default:
5180 PyErr_Format(PyExc_SystemError,
5181 "invalid node type (%d) for annotated assignment",
5182 targ->kind);
5183 return 0;
5184 }
5185 /* Annotation is evaluated last. */
5186 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5187 return 0;
5188 }
5189 return 1;
5190}
5191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005192/* Raises a SyntaxError and returns 0.
5193 If something goes wrong, a different exception may be raised.
5194*/
5195
5196static int
5197compiler_error(struct compiler *c, const char *errstr)
5198{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005199 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005201
Victor Stinner14e461d2013-08-26 22:28:21 +02005202 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 if (!loc) {
5204 Py_INCREF(Py_None);
5205 loc = Py_None;
5206 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005207 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005208 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 if (!u)
5210 goto exit;
5211 v = Py_BuildValue("(zO)", errstr, u);
5212 if (!v)
5213 goto exit;
5214 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005215 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 Py_DECREF(loc);
5217 Py_XDECREF(u);
5218 Py_XDECREF(v);
5219 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220}
5221
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005222/* Emits a SyntaxWarning and returns 1 on success.
5223 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5224 and returns 0.
5225*/
5226static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005227compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005228{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005229 va_list vargs;
5230#ifdef HAVE_STDARG_PROTOTYPES
5231 va_start(vargs, format);
5232#else
5233 va_start(vargs);
5234#endif
5235 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5236 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005237 if (msg == NULL) {
5238 return 0;
5239 }
5240 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5241 c->u->u_lineno, NULL, NULL) < 0)
5242 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005243 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005244 /* Replace the SyntaxWarning exception with a SyntaxError
5245 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005246 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005247 assert(PyUnicode_AsUTF8(msg) != NULL);
5248 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005249 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005250 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005251 return 0;
5252 }
5253 Py_DECREF(msg);
5254 return 1;
5255}
5256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005257static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258compiler_handle_subscr(struct compiler *c, const char *kind,
5259 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 /* XXX this code is duplicated */
5264 switch (ctx) {
5265 case AugLoad: /* fall through to Load */
5266 case Load: op = BINARY_SUBSCR; break;
5267 case AugStore:/* fall through to Store */
5268 case Store: op = STORE_SUBSCR; break;
5269 case Del: op = DELETE_SUBSCR; break;
5270 case Param:
5271 PyErr_Format(PyExc_SystemError,
5272 "invalid %s kind %d in subscript\n",
5273 kind, ctx);
5274 return 0;
5275 }
5276 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005277 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 }
5279 else if (ctx == AugStore) {
5280 ADDOP(c, ROT_THREE);
5281 }
5282 ADDOP(c, op);
5283 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005284}
5285
5286static int
5287compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 int n = 2;
5290 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 /* only handles the cases where BUILD_SLICE is emitted */
5293 if (s->v.Slice.lower) {
5294 VISIT(c, expr, s->v.Slice.lower);
5295 }
5296 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005297 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (s->v.Slice.upper) {
5301 VISIT(c, expr, s->v.Slice.upper);
5302 }
5303 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005304 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 }
5306
5307 if (s->v.Slice.step) {
5308 n++;
5309 VISIT(c, expr, s->v.Slice.step);
5310 }
5311 ADDOP_I(c, BUILD_SLICE, n);
5312 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005313}
5314
5315static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5317 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 switch (s->kind) {
5320 case Slice_kind:
5321 return compiler_slice(c, s, ctx);
5322 case Index_kind:
5323 VISIT(c, expr, s->v.Index.value);
5324 break;
5325 case ExtSlice_kind:
5326 default:
5327 PyErr_SetString(PyExc_SystemError,
5328 "extended slice invalid in nested slice");
5329 return 0;
5330 }
5331 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005332}
5333
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005334static int
5335compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5336{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005337 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 switch (s->kind) {
5339 case Index_kind:
5340 kindname = "index";
5341 if (ctx != AugStore) {
5342 VISIT(c, expr, s->v.Index.value);
5343 }
5344 break;
5345 case Slice_kind:
5346 kindname = "slice";
5347 if (ctx != AugStore) {
5348 if (!compiler_slice(c, s, ctx))
5349 return 0;
5350 }
5351 break;
5352 case ExtSlice_kind:
5353 kindname = "extended slice";
5354 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005355 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 for (i = 0; i < n; i++) {
5357 slice_ty sub = (slice_ty)asdl_seq_GET(
5358 s->v.ExtSlice.dims, i);
5359 if (!compiler_visit_nested_slice(c, sub, ctx))
5360 return 0;
5361 }
5362 ADDOP_I(c, BUILD_TUPLE, n);
5363 }
5364 break;
5365 default:
5366 PyErr_Format(PyExc_SystemError,
5367 "invalid subscript kind %d", s->kind);
5368 return 0;
5369 }
5370 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005371}
5372
Thomas Wouters89f507f2006-12-13 04:49:30 +00005373/* End of the compiler section, beginning of the assembler section */
5374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005376 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377
5378 XXX must handle implicit jumps from one block to next
5379*/
5380
Thomas Wouters89f507f2006-12-13 04:49:30 +00005381struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 PyObject *a_bytecode; /* string containing bytecode */
5383 int a_offset; /* offset into bytecode */
5384 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005385 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 PyObject *a_lnotab; /* string containing lnotab */
5387 int a_lnotab_off; /* offset into lnotab */
5388 int a_lineno; /* last lineno of emitted instruction */
5389 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005390};
5391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005392static void
T. Wouters99b54d62019-09-12 07:05:33 -07005393dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394{
T. Wouters99b54d62019-09-12 07:05:33 -07005395 int i, j;
5396
5397 /* Get rid of recursion for normal control flow.
5398 Since the number of blocks is limited, unused space in a_postorder
5399 (from a_nblocks to end) can be used as a stack for still not ordered
5400 blocks. */
5401 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005402 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005403 assert(a->a_nblocks < j);
5404 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 }
T. Wouters99b54d62019-09-12 07:05:33 -07005406 while (j < end) {
5407 b = a->a_postorder[j++];
5408 for (i = 0; i < b->b_iused; i++) {
5409 struct instr *instr = &b->b_instr[i];
5410 if (instr->i_jrel || instr->i_jabs)
5411 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005412 }
T. Wouters99b54d62019-09-12 07:05:33 -07005413 assert(a->a_nblocks < j);
5414 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005415 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005416}
5417
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005418Py_LOCAL_INLINE(void)
5419stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005421 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005422 if (b->b_startdepth < depth) {
5423 assert(b->b_startdepth < 0);
5424 b->b_startdepth = depth;
5425 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005426 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427}
5428
5429/* Find the flow path that needs the largest stack. We assume that
5430 * cycles in the flow graph have no net effect on the stack depth.
5431 */
5432static int
5433stackdepth(struct compiler *c)
5434{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005435 basicblock *b, *entryblock = NULL;
5436 basicblock **stack, **sp;
5437 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 b->b_startdepth = INT_MIN;
5440 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005441 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 }
5443 if (!entryblock)
5444 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005445 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5446 if (!stack) {
5447 PyErr_NoMemory();
5448 return -1;
5449 }
5450
5451 sp = stack;
5452 stackdepth_push(&sp, entryblock, 0);
5453 while (sp != stack) {
5454 b = *--sp;
5455 int depth = b->b_startdepth;
5456 assert(depth >= 0);
5457 basicblock *next = b->b_next;
5458 for (int i = 0; i < b->b_iused; i++) {
5459 struct instr *instr = &b->b_instr[i];
5460 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5461 if (effect == PY_INVALID_STACK_EFFECT) {
5462 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5463 Py_FatalError("PyCompile_OpcodeStackEffect()");
5464 }
5465 int new_depth = depth + effect;
5466 if (new_depth > maxdepth) {
5467 maxdepth = new_depth;
5468 }
5469 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5470 if (instr->i_jrel || instr->i_jabs) {
5471 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5472 assert(effect != PY_INVALID_STACK_EFFECT);
5473 int target_depth = depth + effect;
5474 if (target_depth > maxdepth) {
5475 maxdepth = target_depth;
5476 }
5477 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005478 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005479 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005480 assert(instr->i_target->b_startdepth >= target_depth);
5481 depth = new_depth;
5482 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005483 }
5484 stackdepth_push(&sp, instr->i_target, target_depth);
5485 }
5486 depth = new_depth;
5487 if (instr->i_opcode == JUMP_ABSOLUTE ||
5488 instr->i_opcode == JUMP_FORWARD ||
5489 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005490 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005491 {
5492 /* remaining code is dead */
5493 next = NULL;
5494 break;
5495 }
5496 }
5497 if (next != NULL) {
5498 stackdepth_push(&sp, next, depth);
5499 }
5500 }
5501 PyObject_Free(stack);
5502 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005503}
5504
5505static int
5506assemble_init(struct assembler *a, int nblocks, int firstlineno)
5507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 memset(a, 0, sizeof(struct assembler));
5509 a->a_lineno = firstlineno;
5510 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5511 if (!a->a_bytecode)
5512 return 0;
5513 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5514 if (!a->a_lnotab)
5515 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005516 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 PyErr_NoMemory();
5518 return 0;
5519 }
T. Wouters99b54d62019-09-12 07:05:33 -07005520 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005522 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 PyErr_NoMemory();
5524 return 0;
5525 }
5526 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005527}
5528
5529static void
5530assemble_free(struct assembler *a)
5531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 Py_XDECREF(a->a_bytecode);
5533 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005534 if (a->a_postorder)
5535 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536}
5537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005538static int
5539blocksize(basicblock *b)
5540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 int i;
5542 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005545 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547}
5548
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005549/* Appends a pair to the end of the line number table, a_lnotab, representing
5550 the instruction's bytecode offset and line number. See
5551 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005552
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005553static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005554assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005557 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005559
Serhiy Storchakaab874002016-09-11 13:48:15 +03005560 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 if(d_bytecode == 0 && d_lineno == 0)
5566 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 if (d_bytecode > 255) {
5569 int j, nbytes, ncodes = d_bytecode / 255;
5570 nbytes = a->a_lnotab_off + 2 * ncodes;
5571 len = PyBytes_GET_SIZE(a->a_lnotab);
5572 if (nbytes >= len) {
5573 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5574 len = nbytes;
5575 else if (len <= INT_MAX / 2)
5576 len *= 2;
5577 else {
5578 PyErr_NoMemory();
5579 return 0;
5580 }
5581 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5582 return 0;
5583 }
5584 lnotab = (unsigned char *)
5585 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5586 for (j = 0; j < ncodes; j++) {
5587 *lnotab++ = 255;
5588 *lnotab++ = 0;
5589 }
5590 d_bytecode -= ncodes * 255;
5591 a->a_lnotab_off += ncodes * 2;
5592 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005593 assert(0 <= d_bytecode && d_bytecode <= 255);
5594
5595 if (d_lineno < -128 || 127 < d_lineno) {
5596 int j, nbytes, ncodes, k;
5597 if (d_lineno < 0) {
5598 k = -128;
5599 /* use division on positive numbers */
5600 ncodes = (-d_lineno) / 128;
5601 }
5602 else {
5603 k = 127;
5604 ncodes = d_lineno / 127;
5605 }
5606 d_lineno -= ncodes * k;
5607 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005608 nbytes = a->a_lnotab_off + 2 * ncodes;
5609 len = PyBytes_GET_SIZE(a->a_lnotab);
5610 if (nbytes >= len) {
5611 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5612 len = nbytes;
5613 else if (len <= INT_MAX / 2)
5614 len *= 2;
5615 else {
5616 PyErr_NoMemory();
5617 return 0;
5618 }
5619 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5620 return 0;
5621 }
5622 lnotab = (unsigned char *)
5623 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5624 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005625 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 d_bytecode = 0;
5627 for (j = 1; j < ncodes; j++) {
5628 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005629 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 a->a_lnotab_off += ncodes * 2;
5632 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005633 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 len = PyBytes_GET_SIZE(a->a_lnotab);
5636 if (a->a_lnotab_off + 2 >= len) {
5637 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5638 return 0;
5639 }
5640 lnotab = (unsigned char *)
5641 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 a->a_lnotab_off += 2;
5644 if (d_bytecode) {
5645 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005646 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 }
5648 else { /* First line of a block; def stmt, etc. */
5649 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005650 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 }
5652 a->a_lineno = i->i_lineno;
5653 a->a_lineno_off = a->a_offset;
5654 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005655}
5656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005657/* assemble_emit()
5658 Extend the bytecode with a new instruction.
5659 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005660*/
5661
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005662static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005663assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005664{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005665 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005667 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005668
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005669 arg = i->i_oparg;
5670 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 if (i->i_lineno && !assemble_lnotab(a, i))
5672 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005673 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 if (len > PY_SSIZE_T_MAX / 2)
5675 return 0;
5676 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5677 return 0;
5678 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005679 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005681 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005683}
5684
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005685static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005686assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005689 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 /* Compute the size of each block and fixup jump args.
5693 Replace block pointer with position in bytecode. */
5694 do {
5695 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005696 for (i = a->a_nblocks - 1; i >= 0; i--) {
5697 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 bsize = blocksize(b);
5699 b->b_offset = totsize;
5700 totsize += bsize;
5701 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005702 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5704 bsize = b->b_offset;
5705 for (i = 0; i < b->b_iused; i++) {
5706 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005707 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 /* Relative jumps are computed relative to
5709 the instruction pointer after fetching
5710 the jump instruction.
5711 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005712 bsize += isize;
5713 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 if (instr->i_jrel) {
5716 instr->i_oparg -= bsize;
5717 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005718 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005719 if (instrsize(instr->i_oparg) != isize) {
5720 extended_arg_recompile = 1;
5721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 }
5724 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 /* XXX: This is an awful hack that could hurt performance, but
5727 on the bright side it should work until we come up
5728 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 The issue is that in the first loop blocksize() is called
5731 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005732 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 So we loop until we stop seeing new EXTENDED_ARGs.
5736 The only EXTENDED_ARGs that could be popping up are
5737 ones in jump instructions. So this should converge
5738 fairly quickly.
5739 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005741}
5742
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005743static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005744dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005747 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 tuple = PyTuple_New(size);
5750 if (tuple == NULL)
5751 return NULL;
5752 while (PyDict_Next(dict, &pos, &k, &v)) {
5753 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005754 Py_INCREF(k);
5755 assert((i - offset) < size);
5756 assert((i - offset) >= 0);
5757 PyTuple_SET_ITEM(tuple, i - offset, k);
5758 }
5759 return tuple;
5760}
5761
5762static PyObject *
5763consts_dict_keys_inorder(PyObject *dict)
5764{
5765 PyObject *consts, *k, *v;
5766 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5767
5768 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5769 if (consts == NULL)
5770 return NULL;
5771 while (PyDict_Next(dict, &pos, &k, &v)) {
5772 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005773 /* The keys of the dictionary can be tuples wrapping a contant.
5774 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5775 * the object we want is always second. */
5776 if (PyTuple_CheckExact(k)) {
5777 k = PyTuple_GET_ITEM(k, 1);
5778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005780 assert(i < size);
5781 assert(i >= 0);
5782 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005784 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005785}
5786
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005787static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005788compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005791 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005792 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005793 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 if (ste->ste_nested)
5795 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005796 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005798 if (!ste->ste_generator && ste->ste_coroutine)
5799 flags |= CO_COROUTINE;
5800 if (ste->ste_generator && ste->ste_coroutine)
5801 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 if (ste->ste_varargs)
5803 flags |= CO_VARARGS;
5804 if (ste->ste_varkeywords)
5805 flags |= CO_VARKEYWORDS;
5806 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 /* (Only) inherit compilerflags in PyCF_MASK */
5809 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005810
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005811 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5812 ste->ste_coroutine &&
5813 !ste->ste_generator) {
5814 flags |= CO_COROUTINE;
5815 }
5816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005818}
5819
INADA Naokic2e16072018-11-26 21:23:22 +09005820// Merge *tuple* with constant cache.
5821// Unlike merge_consts_recursive(), this function doesn't work recursively.
5822static int
5823merge_const_tuple(struct compiler *c, PyObject **tuple)
5824{
5825 assert(PyTuple_CheckExact(*tuple));
5826
5827 PyObject *key = _PyCode_ConstantKey(*tuple);
5828 if (key == NULL) {
5829 return 0;
5830 }
5831
5832 // t is borrowed reference
5833 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5834 Py_DECREF(key);
5835 if (t == NULL) {
5836 return 0;
5837 }
5838 if (t == key) { // tuple is new constant.
5839 return 1;
5840 }
5841
5842 PyObject *u = PyTuple_GET_ITEM(t, 1);
5843 Py_INCREF(u);
5844 Py_DECREF(*tuple);
5845 *tuple = u;
5846 return 1;
5847}
5848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005849static PyCodeObject *
5850makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 PyObject *tmp;
5853 PyCodeObject *co = NULL;
5854 PyObject *consts = NULL;
5855 PyObject *names = NULL;
5856 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 PyObject *name = NULL;
5858 PyObject *freevars = NULL;
5859 PyObject *cellvars = NULL;
5860 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005861 Py_ssize_t nlocals;
5862 int nlocals_int;
5863 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005864 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005865
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005866 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 names = dict_keys_inorder(c->u->u_names, 0);
5868 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5869 if (!consts || !names || !varnames)
5870 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5873 if (!cellvars)
5874 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005875 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 if (!freevars)
5877 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005878
INADA Naokic2e16072018-11-26 21:23:22 +09005879 if (!merge_const_tuple(c, &names) ||
5880 !merge_const_tuple(c, &varnames) ||
5881 !merge_const_tuple(c, &cellvars) ||
5882 !merge_const_tuple(c, &freevars))
5883 {
5884 goto error;
5885 }
5886
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005887 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005888 assert(nlocals < INT_MAX);
5889 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 flags = compute_code_flags(c);
5892 if (flags < 0)
5893 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5896 if (!bytecode)
5897 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5900 if (!tmp)
5901 goto error;
5902 Py_DECREF(consts);
5903 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005904 if (!merge_const_tuple(c, &consts)) {
5905 goto error;
5906 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005908 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005909 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005910 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005911 maxdepth = stackdepth(c);
5912 if (maxdepth < 0) {
5913 goto error;
5914 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005915 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5916 posonlyargcount, kwonlyargcount, nlocals_int,
5917 maxdepth, flags, bytecode, consts, names,
5918 varnames, freevars, cellvars, c->c_filename,
5919 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005920 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 Py_XDECREF(consts);
5922 Py_XDECREF(names);
5923 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 Py_XDECREF(name);
5925 Py_XDECREF(freevars);
5926 Py_XDECREF(cellvars);
5927 Py_XDECREF(bytecode);
5928 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005929}
5930
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005931
5932/* For debugging purposes only */
5933#if 0
5934static void
5935dump_instr(const struct instr *i)
5936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005937 const char *jrel = i->i_jrel ? "jrel " : "";
5938 const char *jabs = i->i_jabs ? "jabs " : "";
5939 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005942 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5946 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005947}
5948
5949static void
5950dump_basicblock(const basicblock *b)
5951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 const char *seen = b->b_seen ? "seen " : "";
5953 const char *b_return = b->b_return ? "return " : "";
5954 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5955 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5956 if (b->b_instr) {
5957 int i;
5958 for (i = 0; i < b->b_iused; i++) {
5959 fprintf(stderr, " [%02d] ", i);
5960 dump_instr(b->b_instr + i);
5961 }
5962 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005963}
5964#endif
5965
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005966static PyCodeObject *
5967assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 basicblock *b, *entryblock;
5970 struct assembler a;
5971 int i, j, nblocks;
5972 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 /* Make sure every block that falls off the end returns None.
5975 XXX NEXT_BLOCK() isn't quite right, because if the last
5976 block ends with a jump or return b_next shouldn't set.
5977 */
5978 if (!c->u->u_curblock->b_return) {
5979 NEXT_BLOCK(c);
5980 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005981 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 ADDOP(c, RETURN_VALUE);
5983 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 nblocks = 0;
5986 entryblock = NULL;
5987 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5988 nblocks++;
5989 entryblock = b;
5990 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 /* Set firstlineno if it wasn't explicitly set. */
5993 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005994 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5996 else
5997 c->u->u_firstlineno = 1;
5998 }
5999 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6000 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006001 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 /* Can't modify the bytecode after computing jump offsets. */
6004 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006005
T. Wouters99b54d62019-09-12 07:05:33 -07006006 /* Emit code in reverse postorder from dfs. */
6007 for (i = a.a_nblocks - 1; i >= 0; i--) {
6008 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006009 for (j = 0; j < b->b_iused; j++)
6010 if (!assemble_emit(&a, &b->b_instr[j]))
6011 goto error;
6012 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6015 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006016 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006020 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 assemble_free(&a);
6022 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006023}
Georg Brandl8334fd92010-12-04 10:26:46 +00006024
6025#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006026PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006027PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6028 PyArena *arena)
6029{
6030 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6031}