blob: a512e9cbd13a16773bb017ea8239a07dfa5e6607 [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 Storchakaed146b52019-08-24 13:41:53 +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;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700164 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;
Miss Islington (bot)92e836c2019-06-12 17:36:03 -0700317 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;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700348 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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001133 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 }
Larry Hastings3a907972013-11-23 14:49:22 -08001135 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136}
1137
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001138int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001139PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1140{
1141 return stack_effect(opcode, oparg, jump);
1142}
1143
1144int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001145PyCompile_OpcodeStackEffect(int opcode, int oparg)
1146{
1147 return stack_effect(opcode, oparg, -1);
1148}
1149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150/* Add an opcode with no argument.
1151 Returns 0 on failure, 1 on success.
1152*/
1153
1154static int
1155compiler_addop(struct compiler *c, int opcode)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 basicblock *b;
1158 struct instr *i;
1159 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001160 assert(!HAS_ARG(opcode));
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001161 if (c->c_do_not_emit_bytecode) {
1162 return 1;
1163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 off = compiler_next_instr(c, c->u->u_curblock);
1165 if (off < 0)
1166 return 0;
1167 b = c->u->u_curblock;
1168 i = &b->b_instr[off];
1169 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001170 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (opcode == RETURN_VALUE)
1172 b->b_return = 1;
1173 compiler_set_lineno(c, off);
1174 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175}
1176
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1179{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001180 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001183 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001185 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001187 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001188 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001189 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return -1;
1192 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001193 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(v);
1195 return -1;
1196 }
1197 Py_DECREF(v);
1198 }
1199 else
1200 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001201 return arg;
1202}
1203
INADA Naokic2e16072018-11-26 21:23:22 +09001204// Merge const *o* recursively and return constant key object.
1205static PyObject*
1206merge_consts_recursive(struct compiler *c, PyObject *o)
1207{
1208 // None and Ellipsis are singleton, and key is the singleton.
1209 // No need to merge object and key.
1210 if (o == Py_None || o == Py_Ellipsis) {
1211 Py_INCREF(o);
1212 return o;
1213 }
1214
1215 PyObject *key = _PyCode_ConstantKey(o);
1216 if (key == NULL) {
1217 return NULL;
1218 }
1219
1220 // t is borrowed reference
1221 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1222 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001223 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001224 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001225 Py_DECREF(key);
1226 return t;
1227 }
1228
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001230 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001232 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 Py_ssize_t len = PyTuple_GET_SIZE(o);
1234 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001235 PyObject *item = PyTuple_GET_ITEM(o, i);
1236 PyObject *u = merge_consts_recursive(c, item);
1237 if (u == NULL) {
1238 Py_DECREF(key);
1239 return NULL;
1240 }
1241
1242 // See _PyCode_ConstantKey()
1243 PyObject *v; // borrowed
1244 if (PyTuple_CheckExact(u)) {
1245 v = PyTuple_GET_ITEM(u, 1);
1246 }
1247 else {
1248 v = u;
1249 }
1250 if (v != item) {
1251 Py_INCREF(v);
1252 PyTuple_SET_ITEM(o, i, v);
1253 Py_DECREF(item);
1254 }
1255
1256 Py_DECREF(u);
1257 }
1258 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001259 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001260 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 // constant keys.
1262 // See _PyCode_ConstantKey() for detail.
1263 assert(PyTuple_CheckExact(key));
1264 assert(PyTuple_GET_SIZE(key) == 2);
1265
1266 Py_ssize_t len = PySet_GET_SIZE(o);
1267 if (len == 0) { // empty frozenset should not be re-created.
1268 return key;
1269 }
1270 PyObject *tuple = PyTuple_New(len);
1271 if (tuple == NULL) {
1272 Py_DECREF(key);
1273 return NULL;
1274 }
1275 Py_ssize_t i = 0, pos = 0;
1276 PyObject *item;
1277 Py_hash_t hash;
1278 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1279 PyObject *k = merge_consts_recursive(c, item);
1280 if (k == NULL) {
1281 Py_DECREF(tuple);
1282 Py_DECREF(key);
1283 return NULL;
1284 }
1285 PyObject *u;
1286 if (PyTuple_CheckExact(k)) {
1287 u = PyTuple_GET_ITEM(k, 1);
1288 Py_INCREF(u);
1289 Py_DECREF(k);
1290 }
1291 else {
1292 u = k;
1293 }
1294 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1295 i++;
1296 }
1297
1298 // Instead of rewriting o, we create new frozenset and embed in the
1299 // key tuple. Caller should get merged frozenset from the key tuple.
1300 PyObject *new = PyFrozenSet_New(tuple);
1301 Py_DECREF(tuple);
1302 if (new == NULL) {
1303 Py_DECREF(key);
1304 return NULL;
1305 }
1306 assert(PyTuple_GET_ITEM(key, 1) == o);
1307 Py_DECREF(o);
1308 PyTuple_SET_ITEM(key, 1, new);
1309 }
INADA Naokic2e16072018-11-26 21:23:22 +09001310
1311 return key;
1312}
1313
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001314static Py_ssize_t
1315compiler_add_const(struct compiler *c, PyObject *o)
1316{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001317 if (c->c_do_not_emit_bytecode) {
1318 return 0;
1319 }
1320
INADA Naokic2e16072018-11-26 21:23:22 +09001321 PyObject *key = merge_consts_recursive(c, o);
1322 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001323 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001324 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325
INADA Naokic2e16072018-11-26 21:23:22 +09001326 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1327 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329}
1330
1331static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001332compiler_addop_load_const(struct compiler *c, PyObject *o)
1333{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001334 if (c->c_do_not_emit_bytecode) {
1335 return 1;
1336 }
1337
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001338 Py_ssize_t arg = compiler_add_const(c, o);
1339 if (arg < 0)
1340 return 0;
1341 return compiler_addop_i(c, LOAD_CONST, arg);
1342}
1343
1344static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001348 if (c->c_do_not_emit_bytecode) {
1349 return 1;
1350 }
1351
Victor Stinnerad9a0662013-11-19 22:23:20 +01001352 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 return compiler_addop_i(c, opcode, arg);
1356}
1357
1358static int
1359compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001362 Py_ssize_t arg;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001363
1364 if (c->c_do_not_emit_bytecode) {
1365 return 1;
1366 }
1367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1369 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001370 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 arg = compiler_add_o(c, dict, mangled);
1372 Py_DECREF(mangled);
1373 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 return compiler_addop_i(c, opcode, arg);
1376}
1377
1378/* Add an opcode with an integer argument.
1379 Returns 0 on failure, 1 on success.
1380*/
1381
1382static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001383compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 struct instr *i;
1386 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001387
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001388 if (c->c_do_not_emit_bytecode) {
1389 return 1;
1390 }
1391
Victor Stinner2ad474b2016-03-01 23:34:47 +01001392 /* oparg value is unsigned, but a signed C int is usually used to store
1393 it in the C code (like Python/ceval.c).
1394
1395 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1396
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001397 The argument of a concrete bytecode instruction is limited to 8-bit.
1398 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1399 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001400 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 off = compiler_next_instr(c, c->u->u_curblock);
1403 if (off < 0)
1404 return 0;
1405 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406 i->i_opcode = opcode;
1407 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 compiler_set_lineno(c, off);
1409 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
1412static int
1413compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 struct instr *i;
1416 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001418 if (c->c_do_not_emit_bytecode) {
1419 return 1;
1420 }
1421
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001422 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 assert(b != NULL);
1424 off = compiler_next_instr(c, c->u->u_curblock);
1425 if (off < 0)
1426 return 0;
1427 i = &c->u->u_curblock->b_instr[off];
1428 i->i_opcode = opcode;
1429 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (absolute)
1431 i->i_jabs = 1;
1432 else
1433 i->i_jrel = 1;
1434 compiler_set_lineno(c, off);
1435 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436}
1437
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001438/* NEXT_BLOCK() creates an implicit jump from the current block
1439 to the new block.
1440
1441 The returns inside this macro make it impossible to decref objects
1442 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (compiler_next_block((C)) == NULL) \
1446 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447}
1448
1449#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!compiler_addop((C), (OP))) \
1451 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452}
1453
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001454#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (!compiler_addop((C), (OP))) { \
1456 compiler_exit_scope(c); \
1457 return 0; \
1458 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001459}
1460
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001461#define ADDOP_LOAD_CONST(C, O) { \
1462 if (!compiler_addop_load_const((C), (O))) \
1463 return 0; \
1464}
1465
1466/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1467#define ADDOP_LOAD_CONST_NEW(C, O) { \
1468 PyObject *__new_const = (O); \
1469 if (__new_const == NULL) { \
1470 return 0; \
1471 } \
1472 if (!compiler_addop_load_const((C), __new_const)) { \
1473 Py_DECREF(__new_const); \
1474 return 0; \
1475 } \
1476 Py_DECREF(__new_const); \
1477}
1478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1481 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482}
1483
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001484/* Same as ADDOP_O, but steals a reference. */
1485#define ADDOP_N(C, OP, O, TYPE) { \
1486 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1487 Py_DECREF((O)); \
1488 return 0; \
1489 } \
1490 Py_DECREF((O)); \
1491}
1492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1495 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_addop_i((C), (OP), (O))) \
1500 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
1503#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (!compiler_addop_j((C), (OP), (O), 1)) \
1505 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506}
1507
1508#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!compiler_addop_j((C), (OP), (O), 0)) \
1510 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511}
1512
1513/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1514 the ASDL name to synthesize the name of the C type and the visit function.
1515*/
1516
1517#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_visit_ ## TYPE((C), (V))) \
1519 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001522#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_visit_ ## TYPE((C), (V))) { \
1524 compiler_exit_scope(c); \
1525 return 0; \
1526 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001527}
1528
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (!compiler_visit_slice((C), (V), (CTX))) \
1531 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532}
1533
1534#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 int _i; \
1536 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1537 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1538 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1539 if (!compiler_visit_ ## TYPE((C), elt)) \
1540 return 0; \
1541 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542}
1543
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001544#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 int _i; \
1546 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1547 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1548 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1549 if (!compiler_visit_ ## TYPE((C), elt)) { \
1550 compiler_exit_scope(c); \
1551 return 0; \
1552 } \
1553 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001554}
1555
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001556/* These macros allows to check only for errors and not emmit bytecode
1557 * while visiting nodes.
1558*/
1559
1560#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1561 c->c_do_not_emit_bytecode++;
1562
1563#define END_DO_NOT_EMIT_BYTECODE \
1564 c->c_do_not_emit_bytecode--; \
1565}
1566
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001567/* Search if variable annotations are present statically in a block. */
1568
1569static int
1570find_ann(asdl_seq *stmts)
1571{
1572 int i, j, res = 0;
1573 stmt_ty st;
1574
1575 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1576 st = (stmt_ty)asdl_seq_GET(stmts, i);
1577 switch (st->kind) {
1578 case AnnAssign_kind:
1579 return 1;
1580 case For_kind:
1581 res = find_ann(st->v.For.body) ||
1582 find_ann(st->v.For.orelse);
1583 break;
1584 case AsyncFor_kind:
1585 res = find_ann(st->v.AsyncFor.body) ||
1586 find_ann(st->v.AsyncFor.orelse);
1587 break;
1588 case While_kind:
1589 res = find_ann(st->v.While.body) ||
1590 find_ann(st->v.While.orelse);
1591 break;
1592 case If_kind:
1593 res = find_ann(st->v.If.body) ||
1594 find_ann(st->v.If.orelse);
1595 break;
1596 case With_kind:
1597 res = find_ann(st->v.With.body);
1598 break;
1599 case AsyncWith_kind:
1600 res = find_ann(st->v.AsyncWith.body);
1601 break;
1602 case Try_kind:
1603 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1604 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1605 st->v.Try.handlers, j);
1606 if (find_ann(handler->v.ExceptHandler.body)) {
1607 return 1;
1608 }
1609 }
1610 res = find_ann(st->v.Try.body) ||
1611 find_ann(st->v.Try.finalbody) ||
1612 find_ann(st->v.Try.orelse);
1613 break;
1614 default:
1615 res = 0;
1616 }
1617 if (res) {
1618 break;
1619 }
1620 }
1621 return res;
1622}
1623
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001624/*
1625 * Frame block handling functions
1626 */
1627
1628static int
1629compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1630 basicblock *exit)
1631{
1632 struct fblockinfo *f;
1633 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1634 PyErr_SetString(PyExc_SyntaxError,
1635 "too many statically nested blocks");
1636 return 0;
1637 }
1638 f = &c->u->u_fblock[c->u->u_nfblocks++];
1639 f->fb_type = t;
1640 f->fb_block = b;
1641 f->fb_exit = exit;
1642 return 1;
1643}
1644
1645static void
1646compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1647{
1648 struct compiler_unit *u = c->u;
1649 assert(u->u_nfblocks > 0);
1650 u->u_nfblocks--;
1651 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1652 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1653}
1654
1655/* Unwind a frame block. If preserve_tos is true, the TOS before
1656 * popping the blocks will be restored afterwards.
1657 */
1658static int
1659compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1660 int preserve_tos)
1661{
1662 switch (info->fb_type) {
1663 case WHILE_LOOP:
1664 return 1;
1665
1666 case FINALLY_END:
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001667 info->fb_exit = NULL;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001668 ADDOP_I(c, POP_FINALLY, preserve_tos);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001669 if (preserve_tos) {
1670 ADDOP(c, ROT_TWO);
1671 }
1672 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001673 return 1;
1674
1675 case FOR_LOOP:
1676 /* Pop the iterator */
1677 if (preserve_tos) {
1678 ADDOP(c, ROT_TWO);
1679 }
1680 ADDOP(c, POP_TOP);
1681 return 1;
1682
1683 case EXCEPT:
1684 ADDOP(c, POP_BLOCK);
1685 return 1;
1686
1687 case FINALLY_TRY:
1688 ADDOP(c, POP_BLOCK);
1689 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1690 return 1;
1691
Serhiy Storchakaed146b52019-08-24 13:41:53 +03001692 case FINALLY_TRY2:
1693 ADDOP(c, POP_BLOCK);
1694 if (preserve_tos) {
1695 ADDOP(c, ROT_TWO);
1696 ADDOP(c, POP_TOP);
1697 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1698 }
1699 else {
1700 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1701 ADDOP(c, POP_TOP);
1702 }
1703 return 1;
1704
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001705 case WITH:
1706 case ASYNC_WITH:
1707 ADDOP(c, POP_BLOCK);
1708 if (preserve_tos) {
1709 ADDOP(c, ROT_TWO);
1710 }
1711 ADDOP(c, BEGIN_FINALLY);
1712 ADDOP(c, WITH_CLEANUP_START);
1713 if (info->fb_type == ASYNC_WITH) {
1714 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001715 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001716 ADDOP(c, YIELD_FROM);
1717 }
1718 ADDOP(c, WITH_CLEANUP_FINISH);
1719 ADDOP_I(c, POP_FINALLY, 0);
1720 return 1;
1721
1722 case HANDLER_CLEANUP:
1723 if (preserve_tos) {
1724 ADDOP(c, ROT_FOUR);
1725 }
1726 if (info->fb_exit) {
1727 ADDOP(c, POP_BLOCK);
1728 ADDOP(c, POP_EXCEPT);
1729 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1730 }
1731 else {
1732 ADDOP(c, POP_EXCEPT);
1733 }
1734 return 1;
1735 }
1736 Py_UNREACHABLE();
1737}
1738
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001739/* Compile a sequence of statements, checking for a docstring
1740 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001741
1742static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001743compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001744{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001745 int i = 0;
1746 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001747 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001748
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001749 /* Set current line number to the line number of first statement.
1750 This way line number for SETUP_ANNOTATIONS will always
1751 coincide with the line number of first "real" statement in module.
Miss Islington (bot)d8071cb2019-10-08 19:42:22 -07001752 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001753 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1754 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001755 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001756 c->u->u_lineno = st->lineno;
1757 }
1758 /* Every annotated class and module should have __annotations__. */
1759 if (find_ann(stmts)) {
1760 ADDOP(c, SETUP_ANNOTATIONS);
1761 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001762 if (!asdl_seq_LEN(stmts))
1763 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001764 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001765 if (c->c_optimize < 2) {
1766 docstring = _PyAST_GetDocString(stmts);
1767 if (docstring) {
1768 i = 1;
1769 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1770 assert(st->kind == Expr_kind);
1771 VISIT(c, expr, st->v.Expr.value);
1772 if (!compiler_nameop(c, __doc__, Store))
1773 return 0;
1774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001776 for (; i < asdl_seq_LEN(stmts); i++)
1777 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779}
1780
1781static PyCodeObject *
1782compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyCodeObject *co;
1785 int addNone = 1;
1786 static PyObject *module;
1787 if (!module) {
1788 module = PyUnicode_InternFromString("<module>");
1789 if (!module)
1790 return NULL;
1791 }
1792 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001793 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return NULL;
1795 switch (mod->kind) {
1796 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001797 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 compiler_exit_scope(c);
1799 return 0;
1800 }
1801 break;
1802 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001803 if (find_ann(mod->v.Interactive.body)) {
1804 ADDOP(c, SETUP_ANNOTATIONS);
1805 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 c->c_interactive = 1;
1807 VISIT_SEQ_IN_SCOPE(c, stmt,
1808 mod->v.Interactive.body);
1809 break;
1810 case Expression_kind:
1811 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1812 addNone = 0;
1813 break;
1814 case Suite_kind:
1815 PyErr_SetString(PyExc_SystemError,
1816 "suite should not be possible");
1817 return 0;
1818 default:
1819 PyErr_Format(PyExc_SystemError,
1820 "module kind %d should not be possible",
1821 mod->kind);
1822 return 0;
1823 }
1824 co = assemble(c, addNone);
1825 compiler_exit_scope(c);
1826 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001827}
1828
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829/* The test for LOCAL must come before the test for FREE in order to
1830 handle classes where name is both local and free. The local var is
1831 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001832*/
1833
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834static int
1835get_ref_type(struct compiler *c, PyObject *name)
1836{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001837 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001838 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001839 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001840 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001841 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (scope == 0) {
1843 char buf[350];
1844 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001845 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001847 PyUnicode_AsUTF8(name),
1848 PyUnicode_AsUTF8(c->u->u_name),
1849 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1850 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1851 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1852 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 );
1854 Py_FatalError(buf);
1855 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858}
1859
1860static int
1861compiler_lookup_arg(PyObject *dict, PyObject *name)
1862{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001863 PyObject *v;
1864 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001866 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001867 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868}
1869
1870static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001871compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001873 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001874 if (qualname == NULL)
1875 qualname = co->co_name;
1876
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001877 if (free) {
1878 for (i = 0; i < free; ++i) {
1879 /* Bypass com_addop_varname because it will generate
1880 LOAD_DEREF but LOAD_CLOSURE is needed.
1881 */
1882 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1883 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 /* Special case: If a class contains a method with a
1886 free variable that has the same name as a method,
1887 the name will be considered free *and* local in the
1888 class. It should be handled by the closure, as
1889 well as by the normal name loookup logic.
1890 */
1891 reftype = get_ref_type(c, name);
1892 if (reftype == CELL)
1893 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1894 else /* (reftype == FREE) */
1895 arg = compiler_lookup_arg(c->u->u_freevars, name);
1896 if (arg == -1) {
1897 fprintf(stderr,
1898 "lookup %s in %s %d %d\n"
1899 "freevars of %s: %s\n",
1900 PyUnicode_AsUTF8(PyObject_Repr(name)),
1901 PyUnicode_AsUTF8(c->u->u_name),
1902 reftype, arg,
1903 PyUnicode_AsUTF8(co->co_name),
1904 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1905 Py_FatalError("compiler_make_closure()");
1906 }
1907 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001909 flags |= 0x08;
1910 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001912 ADDOP_LOAD_CONST(c, (PyObject*)co);
1913 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001914 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916}
1917
1918static int
1919compiler_decorators(struct compiler *c, asdl_seq* decos)
1920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (!decos)
1924 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1927 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1928 }
1929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930}
1931
1932static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001933compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001935{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001936 /* Push a dict of keyword-only default values.
1937
1938 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1939 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001940 int i;
1941 PyObject *keys = NULL;
1942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1944 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1945 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1946 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001947 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001948 if (!mangled) {
1949 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001951 if (keys == NULL) {
1952 keys = PyList_New(1);
1953 if (keys == NULL) {
1954 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001955 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001956 }
1957 PyList_SET_ITEM(keys, 0, mangled);
1958 }
1959 else {
1960 int res = PyList_Append(keys, mangled);
1961 Py_DECREF(mangled);
1962 if (res == -1) {
1963 goto error;
1964 }
1965 }
1966 if (!compiler_visit_expr(c, default_)) {
1967 goto error;
1968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 }
1970 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001971 if (keys != NULL) {
1972 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1973 PyObject *keys_tuple = PyList_AsTuple(keys);
1974 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001975 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001976 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001977 assert(default_count > 0);
1978 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001979 }
1980 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001981 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001982 }
1983
1984error:
1985 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001986 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001987}
1988
1989static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001990compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1991{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001992 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001993 return 1;
1994}
1995
1996static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001997compiler_visit_argannotation(struct compiler *c, identifier id,
1998 expr_ty annotation, PyObject *names)
1999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002001 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002002 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2003 VISIT(c, annexpr, annotation)
2004 }
2005 else {
2006 VISIT(c, expr, annotation);
2007 }
Victor Stinner065efc32014-02-18 22:07:56 +01002008 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002009 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002010 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002011 if (PyList_Append(names, mangled) < 0) {
2012 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002013 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002014 }
2015 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002017 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002018}
2019
2020static int
2021compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2022 PyObject *names)
2023{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002024 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 for (i = 0; i < asdl_seq_LEN(args); i++) {
2026 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002027 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 c,
2029 arg->arg,
2030 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002031 names))
2032 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002034 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002035}
2036
2037static int
2038compiler_visit_annotations(struct compiler *c, arguments_ty args,
2039 expr_ty returns)
2040{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002041 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002043
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002044 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 */
2046 static identifier return_str;
2047 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002048 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 names = PyList_New(0);
2050 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002051 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002052
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002053 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002055 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2056 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002057 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002058 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002059 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002063 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002065 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (!return_str) {
2069 return_str = PyUnicode_InternFromString("return");
2070 if (!return_str)
2071 goto error;
2072 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 goto error;
2075 }
2076
2077 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002079 PyObject *keytuple = PyList_AsTuple(names);
2080 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002081 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002082 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002083 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002085 else {
2086 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002087 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002088 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002089
2090error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002092 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002093}
2094
2095static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002096compiler_visit_defaults(struct compiler *c, arguments_ty args)
2097{
2098 VISIT_SEQ(c, expr, args->defaults);
2099 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2100 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101}
2102
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002103static Py_ssize_t
2104compiler_default_arguments(struct compiler *c, arguments_ty args)
2105{
2106 Py_ssize_t funcflags = 0;
2107 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002108 if (!compiler_visit_defaults(c, args))
2109 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002110 funcflags |= 0x01;
2111 }
2112 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002113 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002114 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002115 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 return -1;
2117 }
2118 else if (res > 0) {
2119 funcflags |= 0x02;
2120 }
2121 }
2122 return funcflags;
2123}
2124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125static int
Yury Selivanov75445082015-05-11 22:57:16 -04002126compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002129 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002130 arguments_ty args;
2131 expr_ty returns;
2132 identifier name;
2133 asdl_seq* decos;
2134 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002135 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002136 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002137 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002138 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139
Yury Selivanov75445082015-05-11 22:57:16 -04002140 if (is_async) {
2141 assert(s->kind == AsyncFunctionDef_kind);
2142
2143 args = s->v.AsyncFunctionDef.args;
2144 returns = s->v.AsyncFunctionDef.returns;
2145 decos = s->v.AsyncFunctionDef.decorator_list;
2146 name = s->v.AsyncFunctionDef.name;
2147 body = s->v.AsyncFunctionDef.body;
2148
2149 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2150 } else {
2151 assert(s->kind == FunctionDef_kind);
2152
2153 args = s->v.FunctionDef.args;
2154 returns = s->v.FunctionDef.returns;
2155 decos = s->v.FunctionDef.decorator_list;
2156 name = s->v.FunctionDef.name;
2157 body = s->v.FunctionDef.body;
2158
2159 scope_type = COMPILER_SCOPE_FUNCTION;
2160 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (!compiler_decorators(c, decos))
2163 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002164
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002165 firstlineno = s->lineno;
2166 if (asdl_seq_LEN(decos)) {
2167 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2168 }
2169
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002170 funcflags = compiler_default_arguments(c, args);
2171 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002173 }
2174
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002175 annotations = compiler_visit_annotations(c, args, returns);
2176 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002177 return 0;
2178 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002179 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002180 funcflags |= 0x04;
2181 }
2182
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002183 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002184 return 0;
2185 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
INADA Naokicb41b272017-02-23 00:31:59 +09002187 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002188 if (c->c_optimize < 2) {
2189 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002190 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002191 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 compiler_exit_scope(c);
2193 return 0;
2194 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002197 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002199 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002201 qualname = c->u->u_qualname;
2202 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002204 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002205 Py_XDECREF(qualname);
2206 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002210 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002211 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* decorators */
2215 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2216 ADDOP_I(c, CALL_FUNCTION, 1);
2217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218
Yury Selivanov75445082015-05-11 22:57:16 -04002219 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220}
2221
2222static int
2223compiler_class(struct compiler *c, stmt_ty s)
2224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyCodeObject *co;
2226 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002227 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (!compiler_decorators(c, decos))
2231 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002232
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002233 firstlineno = s->lineno;
2234 if (asdl_seq_LEN(decos)) {
2235 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2236 }
2237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* ultimately generate code for:
2239 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2240 where:
2241 <func> is a function/closure created from the class body;
2242 it has a single argument (__locals__) where the dict
2243 (or MutableSequence) representing the locals is passed
2244 <name> is the class name
2245 <bases> is the positional arguments and *varargs argument
2246 <keywords> is the keyword arguments and **kwds argument
2247 This borrows from compiler_call.
2248 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002251 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002252 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 return 0;
2254 /* this block represents what we do in the new scope */
2255 {
2256 /* use the class name for name mangling */
2257 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002258 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* load (global) __name__ ... */
2260 str = PyUnicode_InternFromString("__name__");
2261 if (!str || !compiler_nameop(c, str, Load)) {
2262 Py_XDECREF(str);
2263 compiler_exit_scope(c);
2264 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 Py_DECREF(str);
2267 /* ... and store it as __module__ */
2268 str = PyUnicode_InternFromString("__module__");
2269 if (!str || !compiler_nameop(c, str, Store)) {
2270 Py_XDECREF(str);
2271 compiler_exit_scope(c);
2272 return 0;
2273 }
2274 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002275 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002276 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002277 str = PyUnicode_InternFromString("__qualname__");
2278 if (!str || !compiler_nameop(c, str, Store)) {
2279 Py_XDECREF(str);
2280 compiler_exit_scope(c);
2281 return 0;
2282 }
2283 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002285 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 compiler_exit_scope(c);
2287 return 0;
2288 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002289 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002290 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002291 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002292 str = PyUnicode_InternFromString("__class__");
2293 if (str == NULL) {
2294 compiler_exit_scope(c);
2295 return 0;
2296 }
2297 i = compiler_lookup_arg(c->u->u_cellvars, str);
2298 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002299 if (i < 0) {
2300 compiler_exit_scope(c);
2301 return 0;
2302 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002303 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002306 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002307 str = PyUnicode_InternFromString("__classcell__");
2308 if (!str || !compiler_nameop(c, str, Store)) {
2309 Py_XDECREF(str);
2310 compiler_exit_scope(c);
2311 return 0;
2312 }
2313 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002315 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002316 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002317 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002318 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002319 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002320 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* create the code object */
2322 co = assemble(c, 1);
2323 }
2324 /* leave the new scope */
2325 compiler_exit_scope(c);
2326 if (co == NULL)
2327 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* 2. load the 'build_class' function */
2330 ADDOP(c, LOAD_BUILD_CLASS);
2331
2332 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002333 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 Py_DECREF(co);
2335
2336 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002337 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338
2339 /* 5. generate the rest of the code for the call */
2340 if (!compiler_call_helper(c, 2,
2341 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002342 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 return 0;
2344
2345 /* 6. apply decorators */
2346 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2347 ADDOP_I(c, CALL_FUNCTION, 1);
2348 }
2349
2350 /* 7. store into <name> */
2351 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2352 return 0;
2353 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354}
2355
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002356/* Return 0 if the expression is a constant value except named singletons.
2357 Return 1 otherwise. */
2358static int
2359check_is_arg(expr_ty e)
2360{
2361 if (e->kind != Constant_kind) {
2362 return 1;
2363 }
2364 PyObject *value = e->v.Constant.value;
2365 return (value == Py_None
2366 || value == Py_False
2367 || value == Py_True
2368 || value == Py_Ellipsis);
2369}
2370
2371/* Check operands of identity chacks ("is" and "is not").
2372 Emit a warning if any operand is a constant except named singletons.
2373 Return 0 on error.
2374 */
2375static int
2376check_compare(struct compiler *c, expr_ty e)
2377{
2378 Py_ssize_t i, n;
2379 int left = check_is_arg(e->v.Compare.left);
2380 n = asdl_seq_LEN(e->v.Compare.ops);
2381 for (i = 0; i < n; i++) {
2382 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2383 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2384 if (op == Is || op == IsNot) {
2385 if (!right || !left) {
2386 const char *msg = (op == Is)
2387 ? "\"is\" with a literal. Did you mean \"==\"?"
2388 : "\"is not\" with a literal. Did you mean \"!=\"?";
2389 return compiler_warn(c, msg);
2390 }
2391 }
2392 left = right;
2393 }
2394 return 1;
2395}
2396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002398cmpop(cmpop_ty op)
2399{
2400 switch (op) {
2401 case Eq:
2402 return PyCmp_EQ;
2403 case NotEq:
2404 return PyCmp_NE;
2405 case Lt:
2406 return PyCmp_LT;
2407 case LtE:
2408 return PyCmp_LE;
2409 case Gt:
2410 return PyCmp_GT;
2411 case GtE:
2412 return PyCmp_GE;
2413 case Is:
2414 return PyCmp_IS;
2415 case IsNot:
2416 return PyCmp_IS_NOT;
2417 case In:
2418 return PyCmp_IN;
2419 case NotIn:
2420 return PyCmp_NOT_IN;
2421 default:
2422 return PyCmp_BAD;
2423 }
2424}
2425
2426static int
2427compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2428{
2429 switch (e->kind) {
2430 case UnaryOp_kind:
2431 if (e->v.UnaryOp.op == Not)
2432 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2433 /* fallback to general implementation */
2434 break;
2435 case BoolOp_kind: {
2436 asdl_seq *s = e->v.BoolOp.values;
2437 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2438 assert(n >= 0);
2439 int cond2 = e->v.BoolOp.op == Or;
2440 basicblock *next2 = next;
2441 if (!cond2 != !cond) {
2442 next2 = compiler_new_block(c);
2443 if (next2 == NULL)
2444 return 0;
2445 }
2446 for (i = 0; i < n; ++i) {
2447 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2448 return 0;
2449 }
2450 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2451 return 0;
2452 if (next2 != next)
2453 compiler_use_next_block(c, next2);
2454 return 1;
2455 }
2456 case IfExp_kind: {
2457 basicblock *end, *next2;
2458 end = compiler_new_block(c);
2459 if (end == NULL)
2460 return 0;
2461 next2 = compiler_new_block(c);
2462 if (next2 == NULL)
2463 return 0;
2464 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2465 return 0;
2466 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2467 return 0;
2468 ADDOP_JREL(c, JUMP_FORWARD, end);
2469 compiler_use_next_block(c, next2);
2470 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2471 return 0;
2472 compiler_use_next_block(c, end);
2473 return 1;
2474 }
2475 case Compare_kind: {
2476 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2477 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002478 if (!check_compare(c, e)) {
2479 return 0;
2480 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481 basicblock *cleanup = compiler_new_block(c);
2482 if (cleanup == NULL)
2483 return 0;
2484 VISIT(c, expr, e->v.Compare.left);
2485 for (i = 0; i < n; i++) {
2486 VISIT(c, expr,
2487 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2488 ADDOP(c, DUP_TOP);
2489 ADDOP(c, ROT_THREE);
2490 ADDOP_I(c, COMPARE_OP,
2491 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2492 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2493 NEXT_BLOCK(c);
2494 }
2495 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2496 ADDOP_I(c, COMPARE_OP,
2497 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2498 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2499 basicblock *end = compiler_new_block(c);
2500 if (end == NULL)
2501 return 0;
2502 ADDOP_JREL(c, JUMP_FORWARD, end);
2503 compiler_use_next_block(c, cleanup);
2504 ADDOP(c, POP_TOP);
2505 if (!cond) {
2506 ADDOP_JREL(c, JUMP_FORWARD, next);
2507 }
2508 compiler_use_next_block(c, end);
2509 return 1;
2510 }
2511 /* fallback to general implementation */
2512 break;
2513 }
2514 default:
2515 /* fallback to general implementation */
2516 break;
2517 }
2518
2519 /* general implementation */
2520 VISIT(c, expr, e);
2521 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2522 return 1;
2523}
2524
2525static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002526compiler_ifexp(struct compiler *c, expr_ty e)
2527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 basicblock *end, *next;
2529
2530 assert(e->kind == IfExp_kind);
2531 end = compiler_new_block(c);
2532 if (end == NULL)
2533 return 0;
2534 next = compiler_new_block(c);
2535 if (next == NULL)
2536 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002537 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2538 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 VISIT(c, expr, e->v.IfExp.body);
2540 ADDOP_JREL(c, JUMP_FORWARD, end);
2541 compiler_use_next_block(c, next);
2542 VISIT(c, expr, e->v.IfExp.orelse);
2543 compiler_use_next_block(c, end);
2544 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002545}
2546
2547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548compiler_lambda(struct compiler *c, expr_ty e)
2549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002551 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002553 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 arguments_ty args = e->v.Lambda.args;
2555 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (!name) {
2558 name = PyUnicode_InternFromString("<lambda>");
2559 if (!name)
2560 return 0;
2561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002563 funcflags = compiler_default_arguments(c, args);
2564 if (funcflags == -1) {
2565 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002567
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002568 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002569 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 /* Make None the first constant, so the lambda can't have a
2573 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002574 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002578 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2580 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2581 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002582 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 }
2584 else {
2585 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002586 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002588 qualname = c->u->u_qualname;
2589 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002591 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002594 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002595 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 Py_DECREF(co);
2597
2598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599}
2600
2601static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602compiler_if(struct compiler *c, stmt_ty s)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 basicblock *end, *next;
2605 int constant;
2606 assert(s->kind == If_kind);
2607 end = compiler_new_block(c);
2608 if (end == NULL)
2609 return 0;
2610
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002611 constant = expr_constant(s->v.If.test);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002612 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 * constant = 1: "if 1", "if 2", ...
2614 * constant = -1: rest */
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002615 if (constant == 0) {
2616 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 VISIT_SEQ(c, stmt, s->v.If.body);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002618 END_DO_NOT_EMIT_BYTECODE
2619 if (s->v.If.orelse) {
2620 VISIT_SEQ(c, stmt, s->v.If.orelse);
2621 }
2622 } else if (constant == 1) {
2623 VISIT_SEQ(c, stmt, s->v.If.body);
2624 if (s->v.If.orelse) {
2625 BEGIN_DO_NOT_EMIT_BYTECODE
2626 VISIT_SEQ(c, stmt, s->v.If.orelse);
2627 END_DO_NOT_EMIT_BYTECODE
2628 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002630 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 next = compiler_new_block(c);
2632 if (next == NULL)
2633 return 0;
2634 }
2635 else
2636 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002637 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2638 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002640 if (asdl_seq_LEN(s->v.If.orelse)) {
2641 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 compiler_use_next_block(c, next);
2643 VISIT_SEQ(c, stmt, s->v.If.orelse);
2644 }
2645 }
2646 compiler_use_next_block(c, end);
2647 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648}
2649
2650static int
2651compiler_for(struct compiler *c, stmt_ty s)
2652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 start = compiler_new_block(c);
2656 cleanup = compiler_new_block(c);
2657 end = compiler_new_block(c);
2658 if (start == NULL || end == NULL || cleanup == NULL)
2659 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002660
2661 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 VISIT(c, expr, s->v.For.iter);
2665 ADDOP(c, GET_ITER);
2666 compiler_use_next_block(c, start);
2667 ADDOP_JREL(c, FOR_ITER, cleanup);
2668 VISIT(c, expr, s->v.For.target);
2669 VISIT_SEQ(c, stmt, s->v.For.body);
2670 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2671 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002672
2673 compiler_pop_fblock(c, FOR_LOOP, start);
2674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 VISIT_SEQ(c, stmt, s->v.For.orelse);
2676 compiler_use_next_block(c, end);
2677 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678}
2679
Yury Selivanov75445082015-05-11 22:57:16 -04002680
2681static int
2682compiler_async_for(struct compiler *c, stmt_ty s)
2683{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002684 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002685 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2686 c->u->u_ste->ste_coroutine = 1;
2687 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002688 return compiler_error(c, "'async for' outside async function");
2689 }
2690
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002691 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002692 except = compiler_new_block(c);
2693 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002694
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002695 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002696 return 0;
2697
2698 VISIT(c, expr, s->v.AsyncFor.iter);
2699 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002700
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002701 compiler_use_next_block(c, start);
2702 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2703 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002704
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002705 /* SETUP_FINALLY to guard the __anext__ call */
2706 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002707 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002708 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002709 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002710 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002711
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002712 /* Success block for __anext__ */
2713 VISIT(c, expr, s->v.AsyncFor.target);
2714 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2715 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2716
2717 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002718
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002719 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002720 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002721 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002722
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002723 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002724 VISIT_SEQ(c, stmt, s->v.For.orelse);
2725
2726 compiler_use_next_block(c, end);
2727
2728 return 1;
2729}
2730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731static int
2732compiler_while(struct compiler *c, stmt_ty s)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002735 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 if (constant == 0) {
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002738 BEGIN_DO_NOT_EMIT_BYTECODE
2739 VISIT_SEQ(c, stmt, s->v.While.body);
2740 END_DO_NOT_EMIT_BYTECODE
2741 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 VISIT_SEQ(c, stmt, s->v.While.orelse);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return 1;
2745 }
2746 loop = compiler_new_block(c);
2747 end = compiler_new_block(c);
2748 if (constant == -1) {
2749 anchor = compiler_new_block(c);
2750 if (anchor == NULL)
2751 return 0;
2752 }
2753 if (loop == NULL || end == NULL)
2754 return 0;
2755 if (s->v.While.orelse) {
2756 orelse = compiler_new_block(c);
2757 if (orelse == NULL)
2758 return 0;
2759 }
2760 else
2761 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002764 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 return 0;
2766 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002767 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2768 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 }
2770 VISIT_SEQ(c, stmt, s->v.While.body);
2771 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 /* XXX should the two POP instructions be in a separate block
2774 if there is no else clause ?
2775 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002777 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002779 compiler_pop_fblock(c, WHILE_LOOP, loop);
2780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 if (orelse != NULL) /* what if orelse is just pass? */
2782 VISIT_SEQ(c, stmt, s->v.While.orelse);
2783 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786}
2787
2788static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002791 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002792 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 if (c->u->u_ste->ste_type != FunctionBlock)
2794 return compiler_error(c, "'return' outside function");
2795 if (s->v.Return.value != NULL &&
2796 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2797 {
2798 return compiler_error(
2799 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 if (preserve_tos) {
2802 VISIT(c, expr, s->v.Return.value);
2803 }
2804 for (int depth = c->u->u_nfblocks; depth--;) {
2805 struct fblockinfo *info = &c->u->u_fblock[depth];
2806
2807 if (!compiler_unwind_fblock(c, info, preserve_tos))
2808 return 0;
2809 }
2810 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002811 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002812 }
2813 else if (!preserve_tos) {
2814 VISIT(c, expr, s->v.Return.value);
2815 }
2816 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819}
2820
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002821static int
2822compiler_break(struct compiler *c)
2823{
2824 for (int depth = c->u->u_nfblocks; depth--;) {
2825 struct fblockinfo *info = &c->u->u_fblock[depth];
2826
2827 if (!compiler_unwind_fblock(c, info, 0))
2828 return 0;
2829 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2830 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2831 return 1;
2832 }
2833 }
2834 return compiler_error(c, "'break' outside loop");
2835}
2836
2837static int
2838compiler_continue(struct compiler *c)
2839{
2840 for (int depth = c->u->u_nfblocks; depth--;) {
2841 struct fblockinfo *info = &c->u->u_fblock[depth];
2842
2843 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2844 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2845 return 1;
2846 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002847 if (!compiler_unwind_fblock(c, info, 0))
2848 return 0;
2849 }
2850 return compiler_error(c, "'continue' not properly in loop");
2851}
2852
2853
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855
2856 SETUP_FINALLY L
2857 <code for body>
2858 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 BEGIN_FINALLY
2860 L:
2861 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 END_FINALLY
2863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 The special instructions use the block stack. Each block
2865 stack entry contains the instruction that created it (here
2866 SETUP_FINALLY), the level of the value stack at the time the
2867 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 Pushes the current value stack level and the label
2871 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873 Pops en entry from the block stack.
2874 BEGIN_FINALLY
2875 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2878 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 when a SETUP_FINALLY entry is found, the raised and the caught
2882 exceptions are pushed onto the value stack (and the exception
2883 condition is cleared), and the interpreter jumps to the label
2884 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885*/
2886
2887static int
2888compiler_try_finally(struct compiler *c, stmt_ty s)
2889{
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002890 basicblock *start, *newcurblock, *body, *end;
2891 int break_finally = 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 body = compiler_new_block(c);
2894 end = compiler_new_block(c);
2895 if (body == NULL || end == NULL)
2896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002898 start = c->u->u_curblock;
2899
2900 /* `finally` block. Compile it first to determine if any of "break",
2901 "continue" or "return" are used in it. */
2902 compiler_use_next_block(c, end);
2903 if (!compiler_push_fblock(c, FINALLY_END, end, end))
2904 return 0;
2905 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2906 ADDOP(c, END_FINALLY);
2907 break_finally = (c->u->u_fblock[c->u->u_nfblocks - 1].fb_exit == NULL);
2908 if (break_finally) {
2909 /* Pops a placeholder. See below */
2910 ADDOP(c, POP_TOP);
2911 }
2912 compiler_pop_fblock(c, FINALLY_END, end);
2913
2914 newcurblock = c->u->u_curblock;
2915 c->u->u_curblock = start;
2916 start->b_next = NULL;
2917
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002918 /* `try` block */
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002919 c->u->u_lineno_set = 0;
2920 c->u->u_lineno = s->lineno;
2921 c->u->u_col_offset = s->col_offset;
2922 if (break_finally) {
2923 /* Pushes a placeholder for the value of "return" in the "try" block
2924 to balance the stack for "break", "continue" and "return" in
2925 the "finally" block. */
2926 ADDOP_LOAD_CONST(c, Py_None);
2927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 ADDOP_JREL(c, SETUP_FINALLY, end);
2929 compiler_use_next_block(c, body);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002930 if (!compiler_push_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002932 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2933 if (!compiler_try_except(c, s))
2934 return 0;
2935 }
2936 else {
2937 VISIT_SEQ(c, stmt, s->v.Try.body);
2938 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 ADDOP(c, BEGIN_FINALLY);
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002941 compiler_pop_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942
Serhiy Storchakaed146b52019-08-24 13:41:53 +03002943 c->u->u_curblock->b_next = end;
2944 c->u->u_curblock = newcurblock;
2945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947}
2948
2949/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002950 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 (The contents of the value stack is shown in [], with the top
2952 at the right; 'tb' is trace-back info, 'val' the exception's
2953 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954
2955 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002956 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 [] <code for S>
2958 [] POP_BLOCK
2959 [] JUMP_FORWARD L0
2960
2961 [tb, val, exc] L1: DUP )
2962 [tb, val, exc, exc] <evaluate E1> )
2963 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2964 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2965 [tb, val, exc] POP
2966 [tb, val] <assign to V1> (or POP if no V1)
2967 [tb] POP
2968 [] <code for S1>
2969 JUMP_FORWARD L0
2970
2971 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972 .............................etc.......................
2973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2975
2976 [] L0: <next statement>
2977
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 Of course, parts are not generated if Vi or Ei is not present.
2979*/
2980static int
2981compiler_try_except(struct compiler *c, stmt_ty s)
2982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002984 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 body = compiler_new_block(c);
2987 except = compiler_new_block(c);
2988 orelse = compiler_new_block(c);
2989 end = compiler_new_block(c);
2990 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2991 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002992 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002994 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002996 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 ADDOP(c, POP_BLOCK);
2998 compiler_pop_fblock(c, EXCEPT, body);
2999 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003000 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 compiler_use_next_block(c, except);
3002 for (i = 0; i < n; i++) {
3003 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003004 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 if (!handler->v.ExceptHandler.type && i < n-1)
3006 return compiler_error(c, "default 'except:' must be last");
3007 c->u->u_lineno_set = 0;
3008 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003009 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 except = compiler_new_block(c);
3011 if (except == NULL)
3012 return 0;
3013 if (handler->v.ExceptHandler.type) {
3014 ADDOP(c, DUP_TOP);
3015 VISIT(c, expr, handler->v.ExceptHandler.type);
3016 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3017 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3018 }
3019 ADDOP(c, POP_TOP);
3020 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003021 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003022
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003023 cleanup_end = compiler_new_block(c);
3024 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003025 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003026 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003027 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003028
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003029 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3030 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003032 /*
3033 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003034 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003035 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003036 try:
3037 # body
3038 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003039 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003040 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003041 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003043 /* second try: */
3044 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3045 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003046 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003049 /* second # body */
3050 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
3051 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003052 ADDOP(c, BEGIN_FINALLY);
3053 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003055 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003056 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003057 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003060 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003061 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003062 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003063 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02003066 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 }
3069 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003073 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075
Guido van Rossumb940e112007-01-10 16:19:56 +00003076 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 ADDOP(c, POP_TOP);
3078 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003079 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003083 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 }
3085 ADDOP_JREL(c, JUMP_FORWARD, end);
3086 compiler_use_next_block(c, except);
3087 }
3088 ADDOP(c, END_FINALLY);
3089 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003090 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 compiler_use_next_block(c, end);
3092 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093}
3094
3095static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003096compiler_try(struct compiler *c, stmt_ty s) {
3097 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3098 return compiler_try_finally(c, s);
3099 else
3100 return compiler_try_except(c, s);
3101}
3102
3103
3104static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105compiler_import_as(struct compiler *c, identifier name, identifier asname)
3106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 /* The IMPORT_NAME opcode was already generated. This function
3108 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003111 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003113 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3114 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003115 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003116 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003117 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003119 while (1) {
3120 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003122 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003123 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003124 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003125 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003127 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003128 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003129 if (dot == -1) {
3130 break;
3131 }
3132 ADDOP(c, ROT_TWO);
3133 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003135 if (!compiler_nameop(c, asname, Store)) {
3136 return 0;
3137 }
3138 ADDOP(c, POP_TOP);
3139 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 }
3141 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142}
3143
3144static int
3145compiler_import(struct compiler *c, stmt_ty s)
3146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 /* The Import node stores a module name like a.b.c as a single
3148 string. This is convenient for all cases except
3149 import a.b.c as d
3150 where we need to parse that string to extract the individual
3151 module names.
3152 XXX Perhaps change the representation to make this case simpler?
3153 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003154 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 for (i = 0; i < n; i++) {
3157 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3158 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003160 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3161 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 if (alias->asname) {
3165 r = compiler_import_as(c, alias->name, alias->asname);
3166 if (!r)
3167 return r;
3168 }
3169 else {
3170 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 Py_ssize_t dot = PyUnicode_FindChar(
3172 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003173 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003174 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003175 if (tmp == NULL)
3176 return 0;
3177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003179 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 Py_DECREF(tmp);
3181 }
3182 if (!r)
3183 return r;
3184 }
3185 }
3186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187}
3188
3189static int
3190compiler_from_import(struct compiler *c, stmt_ty s)
3191{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003192 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003193 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 if (!empty_string) {
3197 empty_string = PyUnicode_FromString("");
3198 if (!empty_string)
3199 return 0;
3200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003202 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003203
3204 names = PyTuple_New(n);
3205 if (!names)
3206 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* build up the names */
3209 for (i = 0; i < n; i++) {
3210 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3211 Py_INCREF(alias->name);
3212 PyTuple_SET_ITEM(names, i, alias->name);
3213 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003216 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_DECREF(names);
3218 return compiler_error(c, "from __future__ imports must occur "
3219 "at the beginning of the file");
3220 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003221 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 if (s->v.ImportFrom.module) {
3224 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3225 }
3226 else {
3227 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3228 }
3229 for (i = 0; i < n; i++) {
3230 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3231 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003233 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 assert(n == 1);
3235 ADDOP(c, IMPORT_STAR);
3236 return 1;
3237 }
3238
3239 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3240 store_name = alias->name;
3241 if (alias->asname)
3242 store_name = alias->asname;
3243
3244 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 return 0;
3246 }
3247 }
3248 /* remove imported module */
3249 ADDOP(c, POP_TOP);
3250 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251}
3252
3253static int
3254compiler_assert(struct compiler *c, stmt_ty s)
3255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 static PyObject *assertion_error = NULL;
3257 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258
Georg Brandl8334fd92010-12-04 10:26:46 +00003259 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 return 1;
3261 if (assertion_error == NULL) {
3262 assertion_error = PyUnicode_InternFromString("AssertionError");
3263 if (assertion_error == NULL)
3264 return 0;
3265 }
3266 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003267 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3268 {
3269 if (!compiler_warn(c, "assertion is always true, "
3270 "perhaps remove parentheses?"))
3271 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003272 return 0;
3273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 end = compiler_new_block(c);
3276 if (end == NULL)
3277 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003278 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3279 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3281 if (s->v.Assert.msg) {
3282 VISIT(c, expr, s->v.Assert.msg);
3283 ADDOP_I(c, CALL_FUNCTION, 1);
3284 }
3285 ADDOP_I(c, RAISE_VARARGS, 1);
3286 compiler_use_next_block(c, end);
3287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288}
3289
3290static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003291compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3292{
3293 if (c->c_interactive && c->c_nestlevel <= 1) {
3294 VISIT(c, expr, value);
3295 ADDOP(c, PRINT_EXPR);
3296 return 1;
3297 }
3298
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003299 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003300 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003301 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003302 }
3303
3304 VISIT(c, expr, value);
3305 ADDOP(c, POP_TOP);
3306 return 1;
3307}
3308
3309static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310compiler_visit_stmt(struct compiler *c, stmt_ty s)
3311{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003312 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 /* Always assign a lineno to the next instruction for a stmt. */
3315 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003316 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 switch (s->kind) {
3320 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003321 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 case ClassDef_kind:
3323 return compiler_class(c, s);
3324 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003325 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 case Delete_kind:
3327 VISIT_SEQ(c, expr, s->v.Delete.targets)
3328 break;
3329 case Assign_kind:
3330 n = asdl_seq_LEN(s->v.Assign.targets);
3331 VISIT(c, expr, s->v.Assign.value);
3332 for (i = 0; i < n; i++) {
3333 if (i < n - 1)
3334 ADDOP(c, DUP_TOP);
3335 VISIT(c, expr,
3336 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3337 }
3338 break;
3339 case AugAssign_kind:
3340 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003341 case AnnAssign_kind:
3342 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 case For_kind:
3344 return compiler_for(c, s);
3345 case While_kind:
3346 return compiler_while(c, s);
3347 case If_kind:
3348 return compiler_if(c, s);
3349 case Raise_kind:
3350 n = 0;
3351 if (s->v.Raise.exc) {
3352 VISIT(c, expr, s->v.Raise.exc);
3353 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003354 if (s->v.Raise.cause) {
3355 VISIT(c, expr, s->v.Raise.cause);
3356 n++;
3357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003359 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003361 case Try_kind:
3362 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 case Assert_kind:
3364 return compiler_assert(c, s);
3365 case Import_kind:
3366 return compiler_import(c, s);
3367 case ImportFrom_kind:
3368 return compiler_from_import(c, s);
3369 case Global_kind:
3370 case Nonlocal_kind:
3371 break;
3372 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003373 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case Pass_kind:
3375 break;
3376 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003377 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 case Continue_kind:
3379 return compiler_continue(c);
3380 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003381 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003382 case AsyncFunctionDef_kind:
3383 return compiler_function(c, s, 1);
3384 case AsyncWith_kind:
3385 return compiler_async_with(c, s, 0);
3386 case AsyncFor_kind:
3387 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 }
Yury Selivanov75445082015-05-11 22:57:16 -04003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003391}
3392
3393static int
3394unaryop(unaryop_ty op)
3395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 switch (op) {
3397 case Invert:
3398 return UNARY_INVERT;
3399 case Not:
3400 return UNARY_NOT;
3401 case UAdd:
3402 return UNARY_POSITIVE;
3403 case USub:
3404 return UNARY_NEGATIVE;
3405 default:
3406 PyErr_Format(PyExc_SystemError,
3407 "unary op %d should not be possible", op);
3408 return 0;
3409 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410}
3411
3412static int
3413binop(struct compiler *c, operator_ty op)
3414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 switch (op) {
3416 case Add:
3417 return BINARY_ADD;
3418 case Sub:
3419 return BINARY_SUBTRACT;
3420 case Mult:
3421 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003422 case MatMult:
3423 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 case Div:
3425 return BINARY_TRUE_DIVIDE;
3426 case Mod:
3427 return BINARY_MODULO;
3428 case Pow:
3429 return BINARY_POWER;
3430 case LShift:
3431 return BINARY_LSHIFT;
3432 case RShift:
3433 return BINARY_RSHIFT;
3434 case BitOr:
3435 return BINARY_OR;
3436 case BitXor:
3437 return BINARY_XOR;
3438 case BitAnd:
3439 return BINARY_AND;
3440 case FloorDiv:
3441 return BINARY_FLOOR_DIVIDE;
3442 default:
3443 PyErr_Format(PyExc_SystemError,
3444 "binary op %d should not be possible", op);
3445 return 0;
3446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447}
3448
3449static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450inplace_binop(struct compiler *c, operator_ty op)
3451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 switch (op) {
3453 case Add:
3454 return INPLACE_ADD;
3455 case Sub:
3456 return INPLACE_SUBTRACT;
3457 case Mult:
3458 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003459 case MatMult:
3460 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 case Div:
3462 return INPLACE_TRUE_DIVIDE;
3463 case Mod:
3464 return INPLACE_MODULO;
3465 case Pow:
3466 return INPLACE_POWER;
3467 case LShift:
3468 return INPLACE_LSHIFT;
3469 case RShift:
3470 return INPLACE_RSHIFT;
3471 case BitOr:
3472 return INPLACE_OR;
3473 case BitXor:
3474 return INPLACE_XOR;
3475 case BitAnd:
3476 return INPLACE_AND;
3477 case FloorDiv:
3478 return INPLACE_FLOOR_DIVIDE;
3479 default:
3480 PyErr_Format(PyExc_SystemError,
3481 "inplace binary op %d should not be possible", op);
3482 return 0;
3483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484}
3485
3486static int
3487compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3488{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003489 int op, scope;
3490 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 PyObject *dict = c->u->u_names;
3494 PyObject *mangled;
3495 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003497 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3498 !_PyUnicode_EqualToASCIIString(name, "True") &&
3499 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003500
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003501 mangled = _Py_Mangle(c->u->u_private, name);
3502 if (!mangled)
3503 return 0;
3504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 op = 0;
3506 optype = OP_NAME;
3507 scope = PyST_GetScope(c->u->u_ste, mangled);
3508 switch (scope) {
3509 case FREE:
3510 dict = c->u->u_freevars;
3511 optype = OP_DEREF;
3512 break;
3513 case CELL:
3514 dict = c->u->u_cellvars;
3515 optype = OP_DEREF;
3516 break;
3517 case LOCAL:
3518 if (c->u->u_ste->ste_type == FunctionBlock)
3519 optype = OP_FAST;
3520 break;
3521 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003522 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 optype = OP_GLOBAL;
3524 break;
3525 case GLOBAL_EXPLICIT:
3526 optype = OP_GLOBAL;
3527 break;
3528 default:
3529 /* scope can be 0 */
3530 break;
3531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003534 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 switch (optype) {
3537 case OP_DEREF:
3538 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003539 case Load:
3540 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3541 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003542 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003543 op = STORE_DEREF;
3544 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 case AugLoad:
3546 case AugStore:
3547 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003548 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 case Param:
3550 default:
3551 PyErr_SetString(PyExc_SystemError,
3552 "param invalid for deref variable");
3553 return 0;
3554 }
3555 break;
3556 case OP_FAST:
3557 switch (ctx) {
3558 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003559 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003560 op = STORE_FAST;
3561 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 case Del: op = DELETE_FAST; break;
3563 case AugLoad:
3564 case AugStore:
3565 break;
3566 case Param:
3567 default:
3568 PyErr_SetString(PyExc_SystemError,
3569 "param invalid for local variable");
3570 return 0;
3571 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003572 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 return 1;
3574 case OP_GLOBAL:
3575 switch (ctx) {
3576 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003577 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003578 op = STORE_GLOBAL;
3579 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 case Del: op = DELETE_GLOBAL; break;
3581 case AugLoad:
3582 case AugStore:
3583 break;
3584 case Param:
3585 default:
3586 PyErr_SetString(PyExc_SystemError,
3587 "param invalid for global variable");
3588 return 0;
3589 }
3590 break;
3591 case OP_NAME:
3592 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003593 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003594 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003595 op = STORE_NAME;
3596 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 case Del: op = DELETE_NAME; break;
3598 case AugLoad:
3599 case AugStore:
3600 break;
3601 case Param:
3602 default:
3603 PyErr_SetString(PyExc_SystemError,
3604 "param invalid for name variable");
3605 return 0;
3606 }
3607 break;
3608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 assert(op);
3611 arg = compiler_add_o(c, dict, mangled);
3612 Py_DECREF(mangled);
3613 if (arg < 0)
3614 return 0;
3615 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616}
3617
3618static int
3619compiler_boolop(struct compiler *c, expr_ty e)
3620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003622 int jumpi;
3623 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 assert(e->kind == BoolOp_kind);
3627 if (e->v.BoolOp.op == And)
3628 jumpi = JUMP_IF_FALSE_OR_POP;
3629 else
3630 jumpi = JUMP_IF_TRUE_OR_POP;
3631 end = compiler_new_block(c);
3632 if (end == NULL)
3633 return 0;
3634 s = e->v.BoolOp.values;
3635 n = asdl_seq_LEN(s) - 1;
3636 assert(n >= 0);
3637 for (i = 0; i < n; ++i) {
3638 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3639 ADDOP_JABS(c, jumpi, end);
3640 }
3641 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3642 compiler_use_next_block(c, end);
3643 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644}
3645
3646static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003647starunpack_helper(struct compiler *c, asdl_seq *elts,
3648 int single_op, int inner_op, int outer_op)
3649{
3650 Py_ssize_t n = asdl_seq_LEN(elts);
3651 Py_ssize_t i, nsubitems = 0, nseen = 0;
3652 for (i = 0; i < n; i++) {
3653 expr_ty elt = asdl_seq_GET(elts, i);
3654 if (elt->kind == Starred_kind) {
3655 if (nseen) {
3656 ADDOP_I(c, inner_op, nseen);
3657 nseen = 0;
3658 nsubitems++;
3659 }
3660 VISIT(c, expr, elt->v.Starred.value);
3661 nsubitems++;
3662 }
3663 else {
3664 VISIT(c, expr, elt);
3665 nseen++;
3666 }
3667 }
3668 if (nsubitems) {
3669 if (nseen) {
3670 ADDOP_I(c, inner_op, nseen);
3671 nsubitems++;
3672 }
3673 ADDOP_I(c, outer_op, nsubitems);
3674 }
3675 else
3676 ADDOP_I(c, single_op, nseen);
3677 return 1;
3678}
3679
3680static int
3681assignment_helper(struct compiler *c, asdl_seq *elts)
3682{
3683 Py_ssize_t n = asdl_seq_LEN(elts);
3684 Py_ssize_t i;
3685 int seen_star = 0;
3686 for (i = 0; i < n; i++) {
3687 expr_ty elt = asdl_seq_GET(elts, i);
3688 if (elt->kind == Starred_kind && !seen_star) {
3689 if ((i >= (1 << 8)) ||
3690 (n-i-1 >= (INT_MAX >> 8)))
3691 return compiler_error(c,
3692 "too many expressions in "
3693 "star-unpacking assignment");
3694 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3695 seen_star = 1;
3696 asdl_seq_SET(elts, i, elt->v.Starred.value);
3697 }
3698 else if (elt->kind == Starred_kind) {
3699 return compiler_error(c,
3700 "two starred expressions in assignment");
3701 }
3702 }
3703 if (!seen_star) {
3704 ADDOP_I(c, UNPACK_SEQUENCE, n);
3705 }
3706 VISIT_SEQ(c, expr, elts);
3707 return 1;
3708}
3709
3710static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711compiler_list(struct compiler *c, expr_ty e)
3712{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003713 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003714 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003715 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 else if (e->v.List.ctx == Load) {
3718 return starunpack_helper(c, elts,
3719 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721 else
3722 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724}
3725
3726static int
3727compiler_tuple(struct compiler *c, expr_ty e)
3728{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003730 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 return assignment_helper(c, elts);
3732 }
3733 else if (e->v.Tuple.ctx == Load) {
3734 return starunpack_helper(c, elts,
3735 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3736 }
3737 else
3738 VISIT_SEQ(c, expr, elts);
3739 return 1;
3740}
3741
3742static int
3743compiler_set(struct compiler *c, expr_ty e)
3744{
3745 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3746 BUILD_SET, BUILD_SET_UNPACK);
3747}
3748
3749static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003750are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3751{
3752 Py_ssize_t i;
3753 for (i = begin; i < end; i++) {
3754 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003755 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003756 return 0;
3757 }
3758 return 1;
3759}
3760
3761static int
3762compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3763{
3764 Py_ssize_t i, n = end - begin;
3765 PyObject *keys, *key;
3766 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3767 for (i = begin; i < end; i++) {
3768 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3769 }
3770 keys = PyTuple_New(n);
3771 if (keys == NULL) {
3772 return 0;
3773 }
3774 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003775 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003776 Py_INCREF(key);
3777 PyTuple_SET_ITEM(keys, i - begin, key);
3778 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003779 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003780 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3781 }
3782 else {
3783 for (i = begin; i < end; i++) {
3784 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3785 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3786 }
3787 ADDOP_I(c, BUILD_MAP, n);
3788 }
3789 return 1;
3790}
3791
3792static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793compiler_dict(struct compiler *c, expr_ty e)
3794{
Victor Stinner976bb402016-03-23 11:36:19 +01003795 Py_ssize_t i, n, elements;
3796 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 int is_unpacking = 0;
3798 n = asdl_seq_LEN(e->v.Dict.values);
3799 containers = 0;
3800 elements = 0;
3801 for (i = 0; i < n; i++) {
3802 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3803 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 if (!compiler_subdict(c, e, i - elements, i))
3805 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003806 containers++;
3807 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 if (is_unpacking) {
3810 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3811 containers++;
3812 }
3813 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003814 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 }
3816 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003817 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003818 if (!compiler_subdict(c, e, n - elements, n))
3819 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003820 containers++;
3821 }
3822 /* If there is more than one dict, they need to be merged into a new
3823 * dict. If there is one dict and it's an unpacking, then it needs
3824 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003825 if (containers > 1 || is_unpacking) {
3826 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 }
3828 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829}
3830
3831static int
3832compiler_compare(struct compiler *c, expr_ty e)
3833{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003834 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003836 if (!check_compare(c, e)) {
3837 return 0;
3838 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003840 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3841 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3842 if (n == 0) {
3843 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3844 ADDOP_I(c, COMPARE_OP,
3845 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3846 }
3847 else {
3848 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 if (cleanup == NULL)
3850 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003851 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 VISIT(c, expr,
3853 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003854 ADDOP(c, DUP_TOP);
3855 ADDOP(c, ROT_THREE);
3856 ADDOP_I(c, COMPARE_OP,
3857 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3858 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3859 NEXT_BLOCK(c);
3860 }
3861 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3862 ADDOP_I(c, COMPARE_OP,
3863 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 basicblock *end = compiler_new_block(c);
3865 if (end == NULL)
3866 return 0;
3867 ADDOP_JREL(c, JUMP_FORWARD, end);
3868 compiler_use_next_block(c, cleanup);
3869 ADDOP(c, ROT_TWO);
3870 ADDOP(c, POP_TOP);
3871 compiler_use_next_block(c, end);
3872 }
3873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874}
3875
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003876static PyTypeObject *
3877infer_type(expr_ty e)
3878{
3879 switch (e->kind) {
3880 case Tuple_kind:
3881 return &PyTuple_Type;
3882 case List_kind:
3883 case ListComp_kind:
3884 return &PyList_Type;
3885 case Dict_kind:
3886 case DictComp_kind:
3887 return &PyDict_Type;
3888 case Set_kind:
3889 case SetComp_kind:
3890 return &PySet_Type;
3891 case GeneratorExp_kind:
3892 return &PyGen_Type;
3893 case Lambda_kind:
3894 return &PyFunction_Type;
3895 case JoinedStr_kind:
3896 case FormattedValue_kind:
3897 return &PyUnicode_Type;
3898 case Constant_kind:
3899 return e->v.Constant.value->ob_type;
3900 default:
3901 return NULL;
3902 }
3903}
3904
3905static int
3906check_caller(struct compiler *c, expr_ty e)
3907{
3908 switch (e->kind) {
3909 case Constant_kind:
3910 case Tuple_kind:
3911 case List_kind:
3912 case ListComp_kind:
3913 case Dict_kind:
3914 case DictComp_kind:
3915 case Set_kind:
3916 case SetComp_kind:
3917 case GeneratorExp_kind:
3918 case JoinedStr_kind:
3919 case FormattedValue_kind:
3920 return compiler_warn(c, "'%.200s' object is not callable; "
3921 "perhaps you missed a comma?",
3922 infer_type(e)->tp_name);
3923 default:
3924 return 1;
3925 }
3926}
3927
3928static int
3929check_subscripter(struct compiler *c, expr_ty e)
3930{
3931 PyObject *v;
3932
3933 switch (e->kind) {
3934 case Constant_kind:
3935 v = e->v.Constant.value;
3936 if (!(v == Py_None || v == Py_Ellipsis ||
3937 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3938 PyAnySet_Check(v)))
3939 {
3940 return 1;
3941 }
3942 /* fall through */
3943 case Set_kind:
3944 case SetComp_kind:
3945 case GeneratorExp_kind:
3946 case Lambda_kind:
3947 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3948 "perhaps you missed a comma?",
3949 infer_type(e)->tp_name);
3950 default:
3951 return 1;
3952 }
3953}
3954
3955static int
3956check_index(struct compiler *c, expr_ty e, slice_ty s)
3957{
3958 PyObject *v;
3959
3960 if (s->kind != Index_kind) {
3961 return 1;
3962 }
3963 PyTypeObject *index_type = infer_type(s->v.Index.value);
3964 if (index_type == NULL
3965 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3966 || index_type == &PySlice_Type) {
3967 return 1;
3968 }
3969
3970 switch (e->kind) {
3971 case Constant_kind:
3972 v = e->v.Constant.value;
3973 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3974 return 1;
3975 }
3976 /* fall through */
3977 case Tuple_kind:
3978 case List_kind:
3979 case ListComp_kind:
3980 case JoinedStr_kind:
3981 case FormattedValue_kind:
3982 return compiler_warn(c, "%.200s indices must be integers or slices, "
3983 "not %.200s; "
3984 "perhaps you missed a comma?",
3985 infer_type(e)->tp_name,
3986 index_type->tp_name);
3987 default:
3988 return 1;
3989 }
3990}
3991
Zackery Spytz97f5de02019-03-22 01:30:32 -06003992// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003994maybe_optimize_method_call(struct compiler *c, expr_ty e)
3995{
3996 Py_ssize_t argsl, i;
3997 expr_ty meth = e->v.Call.func;
3998 asdl_seq *args = e->v.Call.args;
3999
4000 /* Check that the call node is an attribute access, and that
4001 the call doesn't have keyword parameters. */
4002 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4003 asdl_seq_LEN(e->v.Call.keywords))
4004 return -1;
4005
4006 /* Check that there are no *varargs types of arguments. */
4007 argsl = asdl_seq_LEN(args);
4008 for (i = 0; i < argsl; i++) {
4009 expr_ty elt = asdl_seq_GET(args, i);
4010 if (elt->kind == Starred_kind) {
4011 return -1;
4012 }
4013 }
4014
4015 /* Alright, we can optimize the code. */
4016 VISIT(c, expr, meth->v.Attribute.value);
4017 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4018 VISIT_SEQ(c, expr, e->v.Call.args);
4019 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4020 return 1;
4021}
4022
4023static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024compiler_call(struct compiler *c, expr_ty e)
4025{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004026 int ret = maybe_optimize_method_call(c, e);
4027 if (ret >= 0) {
4028 return ret;
4029 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004030 if (!check_caller(c, e->v.Call.func)) {
4031 return 0;
4032 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 VISIT(c, expr, e->v.Call.func);
4034 return compiler_call_helper(c, 0,
4035 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004036 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004037}
4038
Eric V. Smith235a6f02015-09-19 14:51:32 -04004039static int
4040compiler_joined_str(struct compiler *c, expr_ty e)
4041{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004042 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004043 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4044 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004045 return 1;
4046}
4047
Eric V. Smitha78c7952015-11-03 12:45:05 -05004048/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004049static int
4050compiler_formatted_value(struct compiler *c, expr_ty e)
4051{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004052 /* Our oparg encodes 2 pieces of information: the conversion
4053 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004054
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004055 Convert the conversion char to 3 bits:
4056 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004057 !s : 001 0x1 FVC_STR
4058 !r : 010 0x2 FVC_REPR
4059 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004060
Eric V. Smitha78c7952015-11-03 12:45:05 -05004061 next bit is whether or not we have a format spec:
4062 yes : 100 0x4
4063 no : 000 0x0
4064 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004065
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004066 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004067 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004068
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004069 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004070 VISIT(c, expr, e->v.FormattedValue.value);
4071
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004072 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004073 case 's': oparg = FVC_STR; break;
4074 case 'r': oparg = FVC_REPR; break;
4075 case 'a': oparg = FVC_ASCII; break;
4076 case -1: oparg = FVC_NONE; break;
4077 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004078 PyErr_Format(PyExc_SystemError,
4079 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004080 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004081 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004082 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004083 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004084 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004085 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004086 }
4087
Eric V. Smitha78c7952015-11-03 12:45:05 -05004088 /* And push our opcode and oparg */
4089 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004090
Eric V. Smith235a6f02015-09-19 14:51:32 -04004091 return 1;
4092}
4093
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004094static int
4095compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4096{
4097 Py_ssize_t i, n = end - begin;
4098 keyword_ty kw;
4099 PyObject *keys, *key;
4100 assert(n > 0);
4101 if (n > 1) {
4102 for (i = begin; i < end; i++) {
4103 kw = asdl_seq_GET(keywords, i);
4104 VISIT(c, expr, kw->value);
4105 }
4106 keys = PyTuple_New(n);
4107 if (keys == NULL) {
4108 return 0;
4109 }
4110 for (i = begin; i < end; i++) {
4111 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4112 Py_INCREF(key);
4113 PyTuple_SET_ITEM(keys, i - begin, key);
4114 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004115 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004116 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4117 }
4118 else {
4119 /* a for loop only executes once */
4120 for (i = begin; i < end; i++) {
4121 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004122 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004123 VISIT(c, expr, kw->value);
4124 }
4125 ADDOP_I(c, BUILD_MAP, n);
4126 }
4127 return 1;
4128}
4129
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004130/* shared code between compiler_call and compiler_class */
4131static int
4132compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004133 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004134 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004135 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004136{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004137 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004138 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004139
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004140 /* the number of tuples and dictionaries on the stack */
4141 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4142
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004143 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004144 nkwelts = asdl_seq_LEN(keywords);
4145
4146 for (i = 0; i < nkwelts; i++) {
4147 keyword_ty kw = asdl_seq_GET(keywords, i);
4148 if (kw->arg == NULL) {
4149 mustdictunpack = 1;
4150 break;
4151 }
4152 }
4153
4154 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004155 for (i = 0; i < nelts; i++) {
4156 expr_ty elt = asdl_seq_GET(args, i);
4157 if (elt->kind == Starred_kind) {
4158 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004159 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004160 if (nseen) {
4161 ADDOP_I(c, BUILD_TUPLE, nseen);
4162 nseen = 0;
4163 nsubargs++;
4164 }
4165 VISIT(c, expr, elt->v.Starred.value);
4166 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004167 }
4168 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004169 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004170 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004171 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004173
4174 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004175 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004176 if (nseen) {
4177 /* Pack up any trailing positional arguments. */
4178 ADDOP_I(c, BUILD_TUPLE, nseen);
4179 nsubargs++;
4180 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004181 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004182 /* If we ended up with more than one stararg, we need
4183 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004184 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004185 }
4186 else if (nsubargs == 0) {
4187 ADDOP_I(c, BUILD_TUPLE, 0);
4188 }
4189 nseen = 0; /* the number of keyword arguments on the stack following */
4190 for (i = 0; i < nkwelts; i++) {
4191 keyword_ty kw = asdl_seq_GET(keywords, i);
4192 if (kw->arg == NULL) {
4193 /* A keyword argument unpacking. */
4194 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004195 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4196 return 0;
4197 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004198 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004199 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004200 VISIT(c, expr, kw->value);
4201 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004202 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004203 else {
4204 nseen++;
4205 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004206 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004207 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004208 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004209 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004210 return 0;
4211 nsubkwargs++;
4212 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004213 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004214 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004215 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004216 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004217 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4218 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004220 else if (nkwelts) {
4221 PyObject *names;
4222 VISIT_SEQ(c, keyword, keywords);
4223 names = PyTuple_New(nkwelts);
4224 if (names == NULL) {
4225 return 0;
4226 }
4227 for (i = 0; i < nkwelts; i++) {
4228 keyword_ty kw = asdl_seq_GET(keywords, i);
4229 Py_INCREF(kw->arg);
4230 PyTuple_SET_ITEM(names, i, kw->arg);
4231 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004232 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004233 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4234 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004236 else {
4237 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4238 return 1;
4239 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240}
4241
Nick Coghlan650f0d02007-04-15 12:05:43 +00004242
4243/* List and set comprehensions and generator expressions work by creating a
4244 nested function to perform the actual iteration. This means that the
4245 iteration variables don't leak into the current scope.
4246 The defined function is called immediately following its definition, with the
4247 result of that call being the result of the expression.
4248 The LC/SC version returns the populated container, while the GE version is
4249 flagged in symtable.c as a generator, so it returns the generator object
4250 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004251
4252 Possible cleanups:
4253 - iterate over the generator sequence instead of using recursion
4254*/
4255
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258compiler_comprehension_generator(struct compiler *c,
4259 asdl_seq *generators, int gen_index,
4260 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004262 comprehension_ty gen;
4263 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4264 if (gen->is_async) {
4265 return compiler_async_comprehension_generator(
4266 c, generators, gen_index, elt, val, type);
4267 } else {
4268 return compiler_sync_comprehension_generator(
4269 c, generators, gen_index, elt, val, type);
4270 }
4271}
4272
4273static int
4274compiler_sync_comprehension_generator(struct compiler *c,
4275 asdl_seq *generators, int gen_index,
4276 expr_ty elt, expr_ty val, int type)
4277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 /* generate code for the iterator, then each of the ifs,
4279 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 comprehension_ty gen;
4282 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004283 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 start = compiler_new_block(c);
4286 skip = compiler_new_block(c);
4287 if_cleanup = compiler_new_block(c);
4288 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4291 anchor == NULL)
4292 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (gen_index == 0) {
4297 /* Receive outermost iter as an implicit argument */
4298 c->u->u_argcount = 1;
4299 ADDOP_I(c, LOAD_FAST, 0);
4300 }
4301 else {
4302 /* Sub-iter - calculate on the fly */
4303 VISIT(c, expr, gen->iter);
4304 ADDOP(c, GET_ITER);
4305 }
4306 compiler_use_next_block(c, start);
4307 ADDOP_JREL(c, FOR_ITER, anchor);
4308 NEXT_BLOCK(c);
4309 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 /* XXX this needs to be cleaned up...a lot! */
4312 n = asdl_seq_LEN(gen->ifs);
4313 for (i = 0; i < n; i++) {
4314 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004315 if (!compiler_jump_if(c, e, if_cleanup, 0))
4316 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 NEXT_BLOCK(c);
4318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 if (++gen_index < asdl_seq_LEN(generators))
4321 if (!compiler_comprehension_generator(c,
4322 generators, gen_index,
4323 elt, val, type))
4324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 /* only append after the last for generator */
4327 if (gen_index >= asdl_seq_LEN(generators)) {
4328 /* comprehension specific code */
4329 switch (type) {
4330 case COMP_GENEXP:
4331 VISIT(c, expr, elt);
4332 ADDOP(c, YIELD_VALUE);
4333 ADDOP(c, POP_TOP);
4334 break;
4335 case COMP_LISTCOMP:
4336 VISIT(c, expr, elt);
4337 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4338 break;
4339 case COMP_SETCOMP:
4340 VISIT(c, expr, elt);
4341 ADDOP_I(c, SET_ADD, gen_index + 1);
4342 break;
4343 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004344 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004347 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 ADDOP_I(c, MAP_ADD, gen_index + 1);
4349 break;
4350 default:
4351 return 0;
4352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 compiler_use_next_block(c, skip);
4355 }
4356 compiler_use_next_block(c, if_cleanup);
4357 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4358 compiler_use_next_block(c, anchor);
4359
4360 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361}
4362
4363static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004364compiler_async_comprehension_generator(struct compiler *c,
4365 asdl_seq *generators, int gen_index,
4366 expr_ty elt, expr_ty val, int type)
4367{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004369 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004370 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004371 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004373 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004374
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004375 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376 return 0;
4377 }
4378
4379 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4380
4381 if (gen_index == 0) {
4382 /* Receive outermost iter as an implicit argument */
4383 c->u->u_argcount = 1;
4384 ADDOP_I(c, LOAD_FAST, 0);
4385 }
4386 else {
4387 /* Sub-iter - calculate on the fly */
4388 VISIT(c, expr, gen->iter);
4389 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004390 }
4391
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004392 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004393
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004394 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004395 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004396 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004397 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004398 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004399 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004400
4401 n = asdl_seq_LEN(gen->ifs);
4402 for (i = 0; i < n; i++) {
4403 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004404 if (!compiler_jump_if(c, e, if_cleanup, 0))
4405 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004406 NEXT_BLOCK(c);
4407 }
4408
4409 if (++gen_index < asdl_seq_LEN(generators))
4410 if (!compiler_comprehension_generator(c,
4411 generators, gen_index,
4412 elt, val, type))
4413 return 0;
4414
4415 /* only append after the last for generator */
4416 if (gen_index >= asdl_seq_LEN(generators)) {
4417 /* comprehension specific code */
4418 switch (type) {
4419 case COMP_GENEXP:
4420 VISIT(c, expr, elt);
4421 ADDOP(c, YIELD_VALUE);
4422 ADDOP(c, POP_TOP);
4423 break;
4424 case COMP_LISTCOMP:
4425 VISIT(c, expr, elt);
4426 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4427 break;
4428 case COMP_SETCOMP:
4429 VISIT(c, expr, elt);
4430 ADDOP_I(c, SET_ADD, gen_index + 1);
4431 break;
4432 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004433 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004434 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004435 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004436 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004437 ADDOP_I(c, MAP_ADD, gen_index + 1);
4438 break;
4439 default:
4440 return 0;
4441 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004442 }
4443 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004444 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4445
4446 compiler_use_next_block(c, except);
4447 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004448
4449 return 1;
4450}
4451
4452static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004453compiler_comprehension(struct compiler *c, expr_ty e, int type,
4454 identifier name, asdl_seq *generators, expr_ty elt,
4455 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004458 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004459 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004460 int is_async_function = c->u->u_ste->ste_coroutine;
4461 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004462
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004463 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004464
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004465 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4466 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004467 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004469 }
4470
4471 is_async_generator = c->u->u_ste->ste_coroutine;
4472
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004473 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004474 compiler_error(c, "asynchronous comprehension outside of "
4475 "an asynchronous function");
4476 goto error_in_scope;
4477 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 if (type != COMP_GENEXP) {
4480 int op;
4481 switch (type) {
4482 case COMP_LISTCOMP:
4483 op = BUILD_LIST;
4484 break;
4485 case COMP_SETCOMP:
4486 op = BUILD_SET;
4487 break;
4488 case COMP_DICTCOMP:
4489 op = BUILD_MAP;
4490 break;
4491 default:
4492 PyErr_Format(PyExc_SystemError,
4493 "unknown comprehension type %d", type);
4494 goto error_in_scope;
4495 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 ADDOP_I(c, op, 0);
4498 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (!compiler_comprehension_generator(c, generators, 0, elt,
4501 val, type))
4502 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (type != COMP_GENEXP) {
4505 ADDOP(c, RETURN_VALUE);
4506 }
4507
4508 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004509 qualname = c->u->u_qualname;
4510 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004512 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 goto error;
4514
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004515 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004517 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 Py_DECREF(co);
4519
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 VISIT(c, expr, outermost->iter);
4521
4522 if (outermost->is_async) {
4523 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 } else {
4525 ADDOP(c, GET_ITER);
4526 }
4527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529
4530 if (is_async_generator && type != COMP_GENEXP) {
4531 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004532 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533 ADDOP(c, YIELD_FROM);
4534 }
4535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004537error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004539error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004540 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 Py_XDECREF(co);
4542 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004543}
4544
4545static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004546compiler_genexp(struct compiler *c, expr_ty e)
4547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 static identifier name;
4549 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004550 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 if (!name)
4552 return 0;
4553 }
4554 assert(e->kind == GeneratorExp_kind);
4555 return compiler_comprehension(c, e, COMP_GENEXP, name,
4556 e->v.GeneratorExp.generators,
4557 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004558}
4559
4560static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004561compiler_listcomp(struct compiler *c, expr_ty e)
4562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 static identifier name;
4564 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004565 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (!name)
4567 return 0;
4568 }
4569 assert(e->kind == ListComp_kind);
4570 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4571 e->v.ListComp.generators,
4572 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004573}
4574
4575static int
4576compiler_setcomp(struct compiler *c, expr_ty e)
4577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 static identifier name;
4579 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004580 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (!name)
4582 return 0;
4583 }
4584 assert(e->kind == SetComp_kind);
4585 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4586 e->v.SetComp.generators,
4587 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004588}
4589
4590
4591static int
4592compiler_dictcomp(struct compiler *c, expr_ty e)
4593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 static identifier name;
4595 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004596 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 if (!name)
4598 return 0;
4599 }
4600 assert(e->kind == DictComp_kind);
4601 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4602 e->v.DictComp.generators,
4603 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004604}
4605
4606
4607static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004608compiler_visit_keyword(struct compiler *c, keyword_ty k)
4609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 VISIT(c, expr, k->value);
4611 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004612}
4613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004615 whether they are true or false.
4616
4617 Return values: 1 for true, 0 for false, -1 for non-constant.
4618 */
4619
4620static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004621expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004622{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004623 if (e->kind == Constant_kind) {
4624 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004625 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004626 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004627}
4628
Yury Selivanov75445082015-05-11 22:57:16 -04004629
4630/*
4631 Implements the async with statement.
4632
4633 The semantics outlined in that PEP are as follows:
4634
4635 async with EXPR as VAR:
4636 BLOCK
4637
4638 It is implemented roughly as:
4639
4640 context = EXPR
4641 exit = context.__aexit__ # not calling it
4642 value = await context.__aenter__()
4643 try:
4644 VAR = value # if VAR present in the syntax
4645 BLOCK
4646 finally:
4647 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004648 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004649 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004650 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004651 if not (await exit(*exc)):
4652 raise
4653 */
4654static int
4655compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4656{
4657 basicblock *block, *finally;
4658 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4659
4660 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004661 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4662 c->u->u_ste->ste_coroutine = 1;
4663 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004664 return compiler_error(c, "'async with' outside async function");
4665 }
Yury Selivanov75445082015-05-11 22:57:16 -04004666
4667 block = compiler_new_block(c);
4668 finally = compiler_new_block(c);
4669 if (!block || !finally)
4670 return 0;
4671
4672 /* Evaluate EXPR */
4673 VISIT(c, expr, item->context_expr);
4674
4675 ADDOP(c, BEFORE_ASYNC_WITH);
4676 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004677 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004678 ADDOP(c, YIELD_FROM);
4679
4680 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4681
4682 /* SETUP_ASYNC_WITH pushes a finally block. */
4683 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004684 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004685 return 0;
4686 }
4687
4688 if (item->optional_vars) {
4689 VISIT(c, expr, item->optional_vars);
4690 }
4691 else {
4692 /* Discard result from context.__aenter__() */
4693 ADDOP(c, POP_TOP);
4694 }
4695
4696 pos++;
4697 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4698 /* BLOCK code */
4699 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4700 else if (!compiler_async_with(c, s, pos))
4701 return 0;
4702
4703 /* End of try block; start the finally block */
4704 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004705 ADDOP(c, BEGIN_FINALLY);
4706 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004707
Yury Selivanov75445082015-05-11 22:57:16 -04004708 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004709 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004710 return 0;
4711
4712 /* Finally block starts; context.__exit__ is on the stack under
4713 the exception or return information. Just issue our magic
4714 opcode. */
4715 ADDOP(c, WITH_CLEANUP_START);
4716
4717 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004718 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004719 ADDOP(c, YIELD_FROM);
4720
4721 ADDOP(c, WITH_CLEANUP_FINISH);
4722
4723 /* Finally block ends. */
4724 ADDOP(c, END_FINALLY);
4725 compiler_pop_fblock(c, FINALLY_END, finally);
4726 return 1;
4727}
4728
4729
Guido van Rossumc2e20742006-02-27 22:32:47 +00004730/*
4731 Implements the with statement from PEP 343.
4732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004734
4735 with EXPR as VAR:
4736 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737
Guido van Rossumc2e20742006-02-27 22:32:47 +00004738 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739
Thomas Wouters477c8d52006-05-27 19:21:47 +00004740 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004741 exit = context.__exit__ # not calling it
4742 value = context.__enter__()
4743 try:
4744 VAR = value # if VAR present in the syntax
4745 BLOCK
4746 finally:
4747 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004748 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004749 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004750 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004751 exit(*exc)
4752 */
4753static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004754compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004755{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004756 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004757 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004758
4759 assert(s->kind == With_kind);
4760
Guido van Rossumc2e20742006-02-27 22:32:47 +00004761 block = compiler_new_block(c);
4762 finally = compiler_new_block(c);
4763 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004764 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004765
Thomas Wouters477c8d52006-05-27 19:21:47 +00004766 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004767 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004768 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004769
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004770 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004771 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004772 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004773 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004774 }
4775
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004776 if (item->optional_vars) {
4777 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004778 }
4779 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004781 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004782 }
4783
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004784 pos++;
4785 if (pos == asdl_seq_LEN(s->v.With.items))
4786 /* BLOCK code */
4787 VISIT_SEQ(c, stmt, s->v.With.body)
4788 else if (!compiler_with(c, s, pos))
4789 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004790
4791 /* End of try block; start the finally block */
4792 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004793 ADDOP(c, BEGIN_FINALLY);
4794 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004795
Guido van Rossumc2e20742006-02-27 22:32:47 +00004796 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004797 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004798 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004799
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004800 /* Finally block starts; context.__exit__ is on the stack under
4801 the exception or return information. Just issue our magic
4802 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004803 ADDOP(c, WITH_CLEANUP_START);
4804 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004805
4806 /* Finally block ends. */
4807 ADDOP(c, END_FINALLY);
4808 compiler_pop_fblock(c, FINALLY_END, finally);
4809 return 1;
4810}
4811
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004812static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004813compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004816 case NamedExpr_kind:
4817 VISIT(c, expr, e->v.NamedExpr.value);
4818 ADDOP(c, DUP_TOP);
4819 VISIT(c, expr, e->v.NamedExpr.target);
4820 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 case BoolOp_kind:
4822 return compiler_boolop(c, e);
4823 case BinOp_kind:
4824 VISIT(c, expr, e->v.BinOp.left);
4825 VISIT(c, expr, e->v.BinOp.right);
4826 ADDOP(c, binop(c, e->v.BinOp.op));
4827 break;
4828 case UnaryOp_kind:
4829 VISIT(c, expr, e->v.UnaryOp.operand);
4830 ADDOP(c, unaryop(e->v.UnaryOp.op));
4831 break;
4832 case Lambda_kind:
4833 return compiler_lambda(c, e);
4834 case IfExp_kind:
4835 return compiler_ifexp(c, e);
4836 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004837 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004839 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 case GeneratorExp_kind:
4841 return compiler_genexp(c, e);
4842 case ListComp_kind:
4843 return compiler_listcomp(c, e);
4844 case SetComp_kind:
4845 return compiler_setcomp(c, e);
4846 case DictComp_kind:
4847 return compiler_dictcomp(c, e);
4848 case Yield_kind:
4849 if (c->u->u_ste->ste_type != FunctionBlock)
4850 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004851 if (e->v.Yield.value) {
4852 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 }
4854 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004855 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004857 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004859 case YieldFrom_kind:
4860 if (c->u->u_ste->ste_type != FunctionBlock)
4861 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004862
4863 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4864 return compiler_error(c, "'yield from' inside async function");
4865
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004866 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004867 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004868 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004869 ADDOP(c, YIELD_FROM);
4870 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004871 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004872 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4873 if (c->u->u_ste->ste_type != FunctionBlock){
4874 return compiler_error(c, "'await' outside function");
4875 }
Yury Selivanov75445082015-05-11 22:57:16 -04004876
Victor Stinner331a6a52019-05-27 16:39:22 +02004877 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004878 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4879 return compiler_error(c, "'await' outside async function");
4880 }
4881 }
Yury Selivanov75445082015-05-11 22:57:16 -04004882
4883 VISIT(c, expr, e->v.Await.value);
4884 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004885 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004886 ADDOP(c, YIELD_FROM);
4887 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 case Compare_kind:
4889 return compiler_compare(c, e);
4890 case Call_kind:
4891 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004892 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004893 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004894 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004895 case JoinedStr_kind:
4896 return compiler_joined_str(c, e);
4897 case FormattedValue_kind:
4898 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 /* The following exprs can be assignment targets. */
4900 case Attribute_kind:
4901 if (e->v.Attribute.ctx != AugStore)
4902 VISIT(c, expr, e->v.Attribute.value);
4903 switch (e->v.Attribute.ctx) {
4904 case AugLoad:
4905 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004906 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 case Load:
4908 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4909 break;
4910 case AugStore:
4911 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004912 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 case Store:
4914 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4915 break;
4916 case Del:
4917 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4918 break;
4919 case Param:
4920 default:
4921 PyErr_SetString(PyExc_SystemError,
4922 "param invalid in attribute expression");
4923 return 0;
4924 }
4925 break;
4926 case Subscript_kind:
4927 switch (e->v.Subscript.ctx) {
4928 case AugLoad:
4929 VISIT(c, expr, e->v.Subscript.value);
4930 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4931 break;
4932 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004933 if (!check_subscripter(c, e->v.Subscript.value)) {
4934 return 0;
4935 }
4936 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4937 return 0;
4938 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 VISIT(c, expr, e->v.Subscript.value);
4940 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4941 break;
4942 case AugStore:
4943 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4944 break;
4945 case Store:
4946 VISIT(c, expr, e->v.Subscript.value);
4947 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4948 break;
4949 case Del:
4950 VISIT(c, expr, e->v.Subscript.value);
4951 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4952 break;
4953 case Param:
4954 default:
4955 PyErr_SetString(PyExc_SystemError,
4956 "param invalid in subscript expression");
4957 return 0;
4958 }
4959 break;
4960 case Starred_kind:
4961 switch (e->v.Starred.ctx) {
4962 case Store:
4963 /* In all legitimate cases, the Starred node was already replaced
4964 * by compiler_list/compiler_tuple. XXX: is that okay? */
4965 return compiler_error(c,
4966 "starred assignment target must be in a list or tuple");
4967 default:
4968 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004969 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 case Name_kind:
4972 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4973 /* child nodes of List and Tuple will have expr_context set */
4974 case List_kind:
4975 return compiler_list(c, e);
4976 case Tuple_kind:
4977 return compiler_tuple(c, e);
4978 }
4979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004980}
4981
4982static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004983compiler_visit_expr(struct compiler *c, expr_ty e)
4984{
4985 /* If expr e has a different line number than the last expr/stmt,
4986 set a new line number for the next instruction.
4987 */
4988 int old_lineno = c->u->u_lineno;
4989 int old_col_offset = c->u->u_col_offset;
4990 if (e->lineno != c->u->u_lineno) {
4991 c->u->u_lineno = e->lineno;
4992 c->u->u_lineno_set = 0;
4993 }
4994 /* Updating the column offset is always harmless. */
4995 c->u->u_col_offset = e->col_offset;
4996
4997 int res = compiler_visit_expr1(c, e);
4998
4999 if (old_lineno != c->u->u_lineno) {
5000 c->u->u_lineno = old_lineno;
5001 c->u->u_lineno_set = 0;
5002 }
5003 c->u->u_col_offset = old_col_offset;
5004 return res;
5005}
5006
5007static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005008compiler_augassign(struct compiler *c, stmt_ty s)
5009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 expr_ty e = s->v.AugAssign.target;
5011 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 switch (e->kind) {
5016 case Attribute_kind:
5017 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005018 AugLoad, e->lineno, e->col_offset,
5019 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 if (auge == NULL)
5021 return 0;
5022 VISIT(c, expr, auge);
5023 VISIT(c, expr, s->v.AugAssign.value);
5024 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5025 auge->v.Attribute.ctx = AugStore;
5026 VISIT(c, expr, auge);
5027 break;
5028 case Subscript_kind:
5029 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005030 AugLoad, e->lineno, e->col_offset,
5031 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 if (auge == NULL)
5033 return 0;
5034 VISIT(c, expr, auge);
5035 VISIT(c, expr, s->v.AugAssign.value);
5036 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5037 auge->v.Subscript.ctx = AugStore;
5038 VISIT(c, expr, auge);
5039 break;
5040 case Name_kind:
5041 if (!compiler_nameop(c, e->v.Name.id, Load))
5042 return 0;
5043 VISIT(c, expr, s->v.AugAssign.value);
5044 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5045 return compiler_nameop(c, e->v.Name.id, Store);
5046 default:
5047 PyErr_Format(PyExc_SystemError,
5048 "invalid node type (%d) for augmented assignment",
5049 e->kind);
5050 return 0;
5051 }
5052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005053}
5054
5055static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005056check_ann_expr(struct compiler *c, expr_ty e)
5057{
5058 VISIT(c, expr, e);
5059 ADDOP(c, POP_TOP);
5060 return 1;
5061}
5062
5063static int
5064check_annotation(struct compiler *c, stmt_ty s)
5065{
5066 /* Annotations are only evaluated in a module or class. */
5067 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5068 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5069 return check_ann_expr(c, s->v.AnnAssign.annotation);
5070 }
5071 return 1;
5072}
5073
5074static int
5075check_ann_slice(struct compiler *c, slice_ty sl)
5076{
5077 switch(sl->kind) {
5078 case Index_kind:
5079 return check_ann_expr(c, sl->v.Index.value);
5080 case Slice_kind:
5081 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5082 return 0;
5083 }
5084 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5085 return 0;
5086 }
5087 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5088 return 0;
5089 }
5090 break;
5091 default:
5092 PyErr_SetString(PyExc_SystemError,
5093 "unexpected slice kind");
5094 return 0;
5095 }
5096 return 1;
5097}
5098
5099static int
5100check_ann_subscr(struct compiler *c, slice_ty sl)
5101{
5102 /* We check that everything in a subscript is defined at runtime. */
5103 Py_ssize_t i, n;
5104
5105 switch (sl->kind) {
5106 case Index_kind:
5107 case Slice_kind:
5108 if (!check_ann_slice(c, sl)) {
5109 return 0;
5110 }
5111 break;
5112 case ExtSlice_kind:
5113 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5114 for (i = 0; i < n; i++) {
5115 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5116 switch (subsl->kind) {
5117 case Index_kind:
5118 case Slice_kind:
5119 if (!check_ann_slice(c, subsl)) {
5120 return 0;
5121 }
5122 break;
5123 case ExtSlice_kind:
5124 default:
5125 PyErr_SetString(PyExc_SystemError,
5126 "extended slice invalid in nested slice");
5127 return 0;
5128 }
5129 }
5130 break;
5131 default:
5132 PyErr_Format(PyExc_SystemError,
5133 "invalid subscript kind %d", sl->kind);
5134 return 0;
5135 }
5136 return 1;
5137}
5138
5139static int
5140compiler_annassign(struct compiler *c, stmt_ty s)
5141{
5142 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005143 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005144
5145 assert(s->kind == AnnAssign_kind);
5146
5147 /* We perform the actual assignment first. */
5148 if (s->v.AnnAssign.value) {
5149 VISIT(c, expr, s->v.AnnAssign.value);
5150 VISIT(c, expr, targ);
5151 }
5152 switch (targ->kind) {
5153 case Name_kind:
5154 /* If we have a simple name in a module or class, store annotation. */
5155 if (s->v.AnnAssign.simple &&
5156 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5157 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005158 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5159 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5160 }
5161 else {
5162 VISIT(c, expr, s->v.AnnAssign.annotation);
5163 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005164 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005165 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005166 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005167 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005168 }
5169 break;
5170 case Attribute_kind:
5171 if (!s->v.AnnAssign.value &&
5172 !check_ann_expr(c, targ->v.Attribute.value)) {
5173 return 0;
5174 }
5175 break;
5176 case Subscript_kind:
5177 if (!s->v.AnnAssign.value &&
5178 (!check_ann_expr(c, targ->v.Subscript.value) ||
5179 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5180 return 0;
5181 }
5182 break;
5183 default:
5184 PyErr_Format(PyExc_SystemError,
5185 "invalid node type (%d) for annotated assignment",
5186 targ->kind);
5187 return 0;
5188 }
5189 /* Annotation is evaluated last. */
5190 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5191 return 0;
5192 }
5193 return 1;
5194}
5195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005196/* Raises a SyntaxError and returns 0.
5197 If something goes wrong, a different exception may be raised.
5198*/
5199
5200static int
5201compiler_error(struct compiler *c, const char *errstr)
5202{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005203 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005205
Victor Stinner14e461d2013-08-26 22:28:21 +02005206 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 if (!loc) {
5208 Py_INCREF(Py_None);
5209 loc = Py_None;
5210 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005211 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005212 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 if (!u)
5214 goto exit;
5215 v = Py_BuildValue("(zO)", errstr, u);
5216 if (!v)
5217 goto exit;
5218 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005219 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 Py_DECREF(loc);
5221 Py_XDECREF(u);
5222 Py_XDECREF(v);
5223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005224}
5225
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005226/* Emits a SyntaxWarning and returns 1 on success.
5227 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5228 and returns 0.
5229*/
5230static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005231compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005232{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005233 va_list vargs;
5234#ifdef HAVE_STDARG_PROTOTYPES
5235 va_start(vargs, format);
5236#else
5237 va_start(vargs);
5238#endif
5239 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5240 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005241 if (msg == NULL) {
5242 return 0;
5243 }
5244 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5245 c->u->u_lineno, NULL, NULL) < 0)
5246 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005247 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005248 /* Replace the SyntaxWarning exception with a SyntaxError
5249 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005250 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005251 assert(PyUnicode_AsUTF8(msg) != NULL);
5252 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005253 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005254 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005255 return 0;
5256 }
5257 Py_DECREF(msg);
5258 return 1;
5259}
5260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005261static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262compiler_handle_subscr(struct compiler *c, const char *kind,
5263 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 /* XXX this code is duplicated */
5268 switch (ctx) {
5269 case AugLoad: /* fall through to Load */
5270 case Load: op = BINARY_SUBSCR; break;
5271 case AugStore:/* fall through to Store */
5272 case Store: op = STORE_SUBSCR; break;
5273 case Del: op = DELETE_SUBSCR; break;
5274 case Param:
5275 PyErr_Format(PyExc_SystemError,
5276 "invalid %s kind %d in subscript\n",
5277 kind, ctx);
5278 return 0;
5279 }
5280 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005281 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 }
5283 else if (ctx == AugStore) {
5284 ADDOP(c, ROT_THREE);
5285 }
5286 ADDOP(c, op);
5287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005288}
5289
5290static int
5291compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 int n = 2;
5294 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 /* only handles the cases where BUILD_SLICE is emitted */
5297 if (s->v.Slice.lower) {
5298 VISIT(c, expr, s->v.Slice.lower);
5299 }
5300 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005301 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 if (s->v.Slice.upper) {
5305 VISIT(c, expr, s->v.Slice.upper);
5306 }
5307 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005308 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 }
5310
5311 if (s->v.Slice.step) {
5312 n++;
5313 VISIT(c, expr, s->v.Slice.step);
5314 }
5315 ADDOP_I(c, BUILD_SLICE, n);
5316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317}
5318
5319static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5321 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 switch (s->kind) {
5324 case Slice_kind:
5325 return compiler_slice(c, s, ctx);
5326 case Index_kind:
5327 VISIT(c, expr, s->v.Index.value);
5328 break;
5329 case ExtSlice_kind:
5330 default:
5331 PyErr_SetString(PyExc_SystemError,
5332 "extended slice invalid in nested slice");
5333 return 0;
5334 }
5335 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005336}
5337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005338static int
5339compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5340{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005341 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 switch (s->kind) {
5343 case Index_kind:
5344 kindname = "index";
5345 if (ctx != AugStore) {
5346 VISIT(c, expr, s->v.Index.value);
5347 }
5348 break;
5349 case Slice_kind:
5350 kindname = "slice";
5351 if (ctx != AugStore) {
5352 if (!compiler_slice(c, s, ctx))
5353 return 0;
5354 }
5355 break;
5356 case ExtSlice_kind:
5357 kindname = "extended slice";
5358 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005359 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 for (i = 0; i < n; i++) {
5361 slice_ty sub = (slice_ty)asdl_seq_GET(
5362 s->v.ExtSlice.dims, i);
5363 if (!compiler_visit_nested_slice(c, sub, ctx))
5364 return 0;
5365 }
5366 ADDOP_I(c, BUILD_TUPLE, n);
5367 }
5368 break;
5369 default:
5370 PyErr_Format(PyExc_SystemError,
5371 "invalid subscript kind %d", s->kind);
5372 return 0;
5373 }
5374 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375}
5376
Thomas Wouters89f507f2006-12-13 04:49:30 +00005377/* End of the compiler section, beginning of the assembler section */
5378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379/* do depth-first search of basic block graph, starting with block.
5380 post records the block indices in post-order.
5381
5382 XXX must handle implicit jumps from one block to next
5383*/
5384
Thomas Wouters89f507f2006-12-13 04:49:30 +00005385struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 PyObject *a_bytecode; /* string containing bytecode */
5387 int a_offset; /* offset into bytecode */
5388 int a_nblocks; /* number of reachable blocks */
5389 basicblock **a_postorder; /* list of blocks in dfs postorder */
5390 PyObject *a_lnotab; /* string containing lnotab */
5391 int a_lnotab_off; /* offset into lnotab */
5392 int a_lineno; /* last lineno of emitted instruction */
5393 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005394};
5395
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005396static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005397dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005399 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005401 /* Get rid of recursion for normal control flow.
5402 Since the number of blocks is limited, unused space in a_postorder
5403 (from a_nblocks to end) can be used as a stack for still not ordered
5404 blocks. */
5405 for (j = end; b && !b->b_seen; b = b->b_next) {
5406 b->b_seen = 1;
5407 assert(a->a_nblocks < j);
5408 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005410 while (j < end) {
5411 b = a->a_postorder[j++];
5412 for (i = 0; i < b->b_iused; i++) {
5413 struct instr *instr = &b->b_instr[i];
5414 if (instr->i_jrel || instr->i_jabs)
5415 dfs(c, instr->i_target, a, j);
5416 }
5417 assert(a->a_nblocks < j);
5418 a->a_postorder[a->a_nblocks++] = b;
5419 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420}
5421
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005422Py_LOCAL_INLINE(void)
5423stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005424{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005425 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005426 if (b->b_startdepth < depth) {
5427 assert(b->b_startdepth < 0);
5428 b->b_startdepth = depth;
5429 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431}
5432
5433/* Find the flow path that needs the largest stack. We assume that
5434 * cycles in the flow graph have no net effect on the stack depth.
5435 */
5436static int
5437stackdepth(struct compiler *c)
5438{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 basicblock *b, *entryblock = NULL;
5440 basicblock **stack, **sp;
5441 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 b->b_startdepth = INT_MIN;
5444 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005445 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 }
5447 if (!entryblock)
5448 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005449 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5450 if (!stack) {
5451 PyErr_NoMemory();
5452 return -1;
5453 }
5454
5455 sp = stack;
5456 stackdepth_push(&sp, entryblock, 0);
5457 while (sp != stack) {
5458 b = *--sp;
5459 int depth = b->b_startdepth;
5460 assert(depth >= 0);
5461 basicblock *next = b->b_next;
5462 for (int i = 0; i < b->b_iused; i++) {
5463 struct instr *instr = &b->b_instr[i];
5464 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5465 if (effect == PY_INVALID_STACK_EFFECT) {
5466 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5467 Py_FatalError("PyCompile_OpcodeStackEffect()");
5468 }
5469 int new_depth = depth + effect;
5470 if (new_depth > maxdepth) {
5471 maxdepth = new_depth;
5472 }
5473 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5474 if (instr->i_jrel || instr->i_jabs) {
5475 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5476 assert(effect != PY_INVALID_STACK_EFFECT);
5477 int target_depth = depth + effect;
5478 if (target_depth > maxdepth) {
5479 maxdepth = target_depth;
5480 }
5481 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005482 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005483 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005484 assert(instr->i_target->b_startdepth >= target_depth);
5485 depth = new_depth;
5486 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005487 }
5488 stackdepth_push(&sp, instr->i_target, target_depth);
5489 }
5490 depth = new_depth;
5491 if (instr->i_opcode == JUMP_ABSOLUTE ||
5492 instr->i_opcode == JUMP_FORWARD ||
5493 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005494 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005495 {
5496 /* remaining code is dead */
5497 next = NULL;
5498 break;
5499 }
5500 }
5501 if (next != NULL) {
5502 stackdepth_push(&sp, next, depth);
5503 }
5504 }
5505 PyObject_Free(stack);
5506 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507}
5508
5509static int
5510assemble_init(struct assembler *a, int nblocks, int firstlineno)
5511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 memset(a, 0, sizeof(struct assembler));
5513 a->a_lineno = firstlineno;
5514 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5515 if (!a->a_bytecode)
5516 return 0;
5517 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5518 if (!a->a_lnotab)
5519 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005520 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 PyErr_NoMemory();
5522 return 0;
5523 }
5524 a->a_postorder = (basicblock **)PyObject_Malloc(
5525 sizeof(basicblock *) * nblocks);
5526 if (!a->a_postorder) {
5527 PyErr_NoMemory();
5528 return 0;
5529 }
5530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005531}
5532
5533static void
5534assemble_free(struct assembler *a)
5535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 Py_XDECREF(a->a_bytecode);
5537 Py_XDECREF(a->a_lnotab);
5538 if (a->a_postorder)
5539 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005540}
5541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005542static int
5543blocksize(basicblock *b)
5544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 int i;
5546 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005549 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005551}
5552
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005553/* Appends a pair to the end of the line number table, a_lnotab, representing
5554 the instruction's bytecode offset and line number. See
5555 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005556
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005557static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005558assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005561 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005563
Serhiy Storchakaab874002016-09-11 13:48:15 +03005564 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 if(d_bytecode == 0 && d_lineno == 0)
5570 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 if (d_bytecode > 255) {
5573 int j, nbytes, ncodes = d_bytecode / 255;
5574 nbytes = a->a_lnotab_off + 2 * ncodes;
5575 len = PyBytes_GET_SIZE(a->a_lnotab);
5576 if (nbytes >= len) {
5577 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5578 len = nbytes;
5579 else if (len <= INT_MAX / 2)
5580 len *= 2;
5581 else {
5582 PyErr_NoMemory();
5583 return 0;
5584 }
5585 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5586 return 0;
5587 }
5588 lnotab = (unsigned char *)
5589 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5590 for (j = 0; j < ncodes; j++) {
5591 *lnotab++ = 255;
5592 *lnotab++ = 0;
5593 }
5594 d_bytecode -= ncodes * 255;
5595 a->a_lnotab_off += ncodes * 2;
5596 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005597 assert(0 <= d_bytecode && d_bytecode <= 255);
5598
5599 if (d_lineno < -128 || 127 < d_lineno) {
5600 int j, nbytes, ncodes, k;
5601 if (d_lineno < 0) {
5602 k = -128;
5603 /* use division on positive numbers */
5604 ncodes = (-d_lineno) / 128;
5605 }
5606 else {
5607 k = 127;
5608 ncodes = d_lineno / 127;
5609 }
5610 d_lineno -= ncodes * k;
5611 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 nbytes = a->a_lnotab_off + 2 * ncodes;
5613 len = PyBytes_GET_SIZE(a->a_lnotab);
5614 if (nbytes >= len) {
5615 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5616 len = nbytes;
5617 else if (len <= INT_MAX / 2)
5618 len *= 2;
5619 else {
5620 PyErr_NoMemory();
5621 return 0;
5622 }
5623 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5624 return 0;
5625 }
5626 lnotab = (unsigned char *)
5627 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5628 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005629 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 d_bytecode = 0;
5631 for (j = 1; j < ncodes; j++) {
5632 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005633 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 a->a_lnotab_off += ncodes * 2;
5636 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005637 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 len = PyBytes_GET_SIZE(a->a_lnotab);
5640 if (a->a_lnotab_off + 2 >= len) {
5641 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5642 return 0;
5643 }
5644 lnotab = (unsigned char *)
5645 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 a->a_lnotab_off += 2;
5648 if (d_bytecode) {
5649 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005650 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 }
5652 else { /* First line of a block; def stmt, etc. */
5653 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005654 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 }
5656 a->a_lineno = i->i_lineno;
5657 a->a_lineno_off = a->a_offset;
5658 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005659}
5660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005661/* assemble_emit()
5662 Extend the bytecode with a new instruction.
5663 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005664*/
5665
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005667assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005668{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005669 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005671 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005672
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005673 arg = i->i_oparg;
5674 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 if (i->i_lineno && !assemble_lnotab(a, i))
5676 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005677 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 if (len > PY_SSIZE_T_MAX / 2)
5679 return 0;
5680 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5681 return 0;
5682 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005683 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005685 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005687}
5688
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005689static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005690assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005693 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 /* Compute the size of each block and fixup jump args.
5697 Replace block pointer with position in bytecode. */
5698 do {
5699 totsize = 0;
5700 for (i = a->a_nblocks - 1; i >= 0; i--) {
5701 b = a->a_postorder[i];
5702 bsize = blocksize(b);
5703 b->b_offset = totsize;
5704 totsize += bsize;
5705 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005706 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5708 bsize = b->b_offset;
5709 for (i = 0; i < b->b_iused; i++) {
5710 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005711 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 /* Relative jumps are computed relative to
5713 the instruction pointer after fetching
5714 the jump instruction.
5715 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005716 bsize += isize;
5717 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005719 if (instr->i_jrel) {
5720 instr->i_oparg -= bsize;
5721 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005722 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005723 if (instrsize(instr->i_oparg) != isize) {
5724 extended_arg_recompile = 1;
5725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 }
5728 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 /* XXX: This is an awful hack that could hurt performance, but
5731 on the bright side it should work until we come up
5732 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 The issue is that in the first loop blocksize() is called
5735 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005736 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005737 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 So we loop until we stop seeing new EXTENDED_ARGs.
5740 The only EXTENDED_ARGs that could be popping up are
5741 ones in jump instructions. So this should converge
5742 fairly quickly.
5743 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005744 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005745}
5746
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005747static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005748dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005751 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 tuple = PyTuple_New(size);
5754 if (tuple == NULL)
5755 return NULL;
5756 while (PyDict_Next(dict, &pos, &k, &v)) {
5757 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005758 Py_INCREF(k);
5759 assert((i - offset) < size);
5760 assert((i - offset) >= 0);
5761 PyTuple_SET_ITEM(tuple, i - offset, k);
5762 }
5763 return tuple;
5764}
5765
5766static PyObject *
5767consts_dict_keys_inorder(PyObject *dict)
5768{
5769 PyObject *consts, *k, *v;
5770 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5771
5772 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5773 if (consts == NULL)
5774 return NULL;
5775 while (PyDict_Next(dict, &pos, &k, &v)) {
5776 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005777 /* The keys of the dictionary can be tuples wrapping a contant.
5778 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5779 * the object we want is always second. */
5780 if (PyTuple_CheckExact(k)) {
5781 k = PyTuple_GET_ITEM(k, 1);
5782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005784 assert(i < size);
5785 assert(i >= 0);
5786 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005788 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005789}
5790
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005791static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005792compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005795 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005797 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 if (ste->ste_nested)
5799 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005800 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005802 if (!ste->ste_generator && ste->ste_coroutine)
5803 flags |= CO_COROUTINE;
5804 if (ste->ste_generator && ste->ste_coroutine)
5805 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 if (ste->ste_varargs)
5807 flags |= CO_VARARGS;
5808 if (ste->ste_varkeywords)
5809 flags |= CO_VARKEYWORDS;
5810 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 /* (Only) inherit compilerflags in PyCF_MASK */
5813 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005814
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005815 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5816 ste->ste_coroutine &&
5817 !ste->ste_generator) {
5818 flags |= CO_COROUTINE;
5819 }
5820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005822}
5823
INADA Naokic2e16072018-11-26 21:23:22 +09005824// Merge *tuple* with constant cache.
5825// Unlike merge_consts_recursive(), this function doesn't work recursively.
5826static int
5827merge_const_tuple(struct compiler *c, PyObject **tuple)
5828{
5829 assert(PyTuple_CheckExact(*tuple));
5830
5831 PyObject *key = _PyCode_ConstantKey(*tuple);
5832 if (key == NULL) {
5833 return 0;
5834 }
5835
5836 // t is borrowed reference
5837 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5838 Py_DECREF(key);
5839 if (t == NULL) {
5840 return 0;
5841 }
5842 if (t == key) { // tuple is new constant.
5843 return 1;
5844 }
5845
5846 PyObject *u = PyTuple_GET_ITEM(t, 1);
5847 Py_INCREF(u);
5848 Py_DECREF(*tuple);
5849 *tuple = u;
5850 return 1;
5851}
5852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005853static PyCodeObject *
5854makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 PyObject *tmp;
5857 PyCodeObject *co = NULL;
5858 PyObject *consts = NULL;
5859 PyObject *names = NULL;
5860 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 PyObject *name = NULL;
5862 PyObject *freevars = NULL;
5863 PyObject *cellvars = NULL;
5864 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005865 Py_ssize_t nlocals;
5866 int nlocals_int;
5867 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005868 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005869
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005870 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 names = dict_keys_inorder(c->u->u_names, 0);
5872 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5873 if (!consts || !names || !varnames)
5874 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5877 if (!cellvars)
5878 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005879 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 if (!freevars)
5881 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005882
INADA Naokic2e16072018-11-26 21:23:22 +09005883 if (!merge_const_tuple(c, &names) ||
5884 !merge_const_tuple(c, &varnames) ||
5885 !merge_const_tuple(c, &cellvars) ||
5886 !merge_const_tuple(c, &freevars))
5887 {
5888 goto error;
5889 }
5890
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005891 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005892 assert(nlocals < INT_MAX);
5893 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 flags = compute_code_flags(c);
5896 if (flags < 0)
5897 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5900 if (!bytecode)
5901 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5904 if (!tmp)
5905 goto error;
5906 Py_DECREF(consts);
5907 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005908 if (!merge_const_tuple(c, &consts)) {
5909 goto error;
5910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005912 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005913 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005914 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005915 maxdepth = stackdepth(c);
5916 if (maxdepth < 0) {
5917 goto error;
5918 }
Miss Islington (bot)cb083f72019-07-01 04:29:14 -07005919 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5920 posonlyargcount, kwonlyargcount, nlocals_int,
5921 maxdepth, flags, bytecode, consts, names,
5922 varnames, freevars, cellvars, c->c_filename,
5923 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005924 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 Py_XDECREF(consts);
5926 Py_XDECREF(names);
5927 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 Py_XDECREF(name);
5929 Py_XDECREF(freevars);
5930 Py_XDECREF(cellvars);
5931 Py_XDECREF(bytecode);
5932 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005933}
5934
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005935
5936/* For debugging purposes only */
5937#if 0
5938static void
5939dump_instr(const struct instr *i)
5940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 const char *jrel = i->i_jrel ? "jrel " : "";
5942 const char *jabs = i->i_jabs ? "jabs " : "";
5943 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005946 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005947 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5950 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005951}
5952
5953static void
5954dump_basicblock(const basicblock *b)
5955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 const char *seen = b->b_seen ? "seen " : "";
5957 const char *b_return = b->b_return ? "return " : "";
5958 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5959 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5960 if (b->b_instr) {
5961 int i;
5962 for (i = 0; i < b->b_iused; i++) {
5963 fprintf(stderr, " [%02d] ", i);
5964 dump_instr(b->b_instr + i);
5965 }
5966 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005967}
5968#endif
5969
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005970static PyCodeObject *
5971assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 basicblock *b, *entryblock;
5974 struct assembler a;
5975 int i, j, nblocks;
5976 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 /* Make sure every block that falls off the end returns None.
5979 XXX NEXT_BLOCK() isn't quite right, because if the last
5980 block ends with a jump or return b_next shouldn't set.
5981 */
5982 if (!c->u->u_curblock->b_return) {
5983 NEXT_BLOCK(c);
5984 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005985 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 ADDOP(c, RETURN_VALUE);
5987 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989 nblocks = 0;
5990 entryblock = NULL;
5991 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5992 nblocks++;
5993 entryblock = b;
5994 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 /* Set firstlineno if it wasn't explicitly set. */
5997 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005998 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6000 else
6001 c->u->u_firstlineno = 1;
6002 }
6003 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6004 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006005 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 /* Can't modify the bytecode after computing jump offsets. */
6008 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 /* Emit code in reverse postorder from dfs. */
6011 for (i = a.a_nblocks - 1; i >= 0; i--) {
6012 b = a.a_postorder[i];
6013 for (j = 0; j < b->b_iused; j++)
6014 if (!assemble_emit(&a, &b->b_instr[j]))
6015 goto error;
6016 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6019 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006020 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006024 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 assemble_free(&a);
6026 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006027}
Georg Brandl8334fd92010-12-04 10:26:46 +00006028
6029#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006030PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006031PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6032 PyArena *arena)
6033{
6034 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6035}