blob: f26ad3c775255155215eb93f5028eef2c7d85a9a [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Victor Stinnerc96be812019-05-14 17:34:56 +020027#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Serhiy Storchakaef61c522019-08-24 13:11:52 +030084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_TRY2, FINALLY_END,
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020085 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
Antoine Pitrou86a36b52011-11-25 18:56:07 +010094enum {
95 COMPILER_SCOPE_MODULE,
96 COMPILER_SCOPE_CLASS,
97 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040098 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040099 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100 COMPILER_SCOPE_COMPREHENSION,
101};
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103/* The following items change on entry and exit of code blocks.
104 They must be saved and restored when returning to a block.
105*/
106struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400110 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100111 int u_scope_type;
112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 /* The following fields are dicts that map objects to
114 the index of them in co_XXX. The index is used as
115 the argument for opcodes that refer to those collections.
116 */
117 PyObject *u_consts; /* all constants */
118 PyObject *u_names; /* all names */
119 PyObject *u_varnames; /* local variables */
120 PyObject *u_cellvars; /* cell variables */
121 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Victor Stinnerf8e32212013-11-19 23:56:34 +0100125 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100126 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 /* Pointer to the most recently allocated block. By following b_list
129 members, you can reach all early allocated blocks. */
130 basicblock *u_blocks;
131 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int u_nfblocks;
134 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_firstlineno; /* the first lineno of the block */
137 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000138 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_lineno_set; /* boolean to indicate whether instr
140 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141};
142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000148
149Note that we don't track recursion levels during compilation - the
150task of detecting and rejecting excessive levels of nesting is
151handled by the symbol analysis pass.
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153*/
154
155struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200156 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 struct symtable *c_st;
158 PyFutureFeatures *c_future; /* pointer to module's __future__ */
159 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Georg Brandl8334fd92010-12-04 10:26:46 +0000161 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 int c_interactive; /* true if in interactive mode */
163 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100164 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
165 if this value is different from zero.
166 This can be used to temporarily visit
167 nodes without emitting bytecode to
168 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
INADA Naokic2e16072018-11-26 21:23:22 +0900170 PyObject *c_const_cache; /* Python dict holding all constants,
171 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 struct compiler_unit *u; /* compiler state for current block */
173 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
174 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175};
176
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100177static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static void compiler_free(struct compiler *);
179static basicblock *compiler_new_block(struct compiler *);
180static int compiler_next_instr(struct compiler *, basicblock *);
181static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100182static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200185static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
187
188static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
189static int compiler_visit_stmt(struct compiler *, stmt_ty);
190static int compiler_visit_keyword(struct compiler *, keyword_ty);
191static int compiler_visit_expr(struct compiler *, expr_ty);
192static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700193static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200198static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500200static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400201static int compiler_async_with(struct compiler *, stmt_ty, int);
202static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100203static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400205 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500206static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400207static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000208
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700209static int compiler_sync_comprehension_generator(
210 struct compiler *c,
211 asdl_seq *generators, int gen_index,
212 expr_ty elt, expr_ty val, int type);
213
214static int compiler_async_comprehension_generator(
215 struct compiler *c,
216 asdl_seq *generators, int gen_index,
217 expr_ty elt, expr_ty val, int type);
218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000220static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400222#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000225_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Name mangling: __private becomes _classname__private.
228 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyObject *result;
230 size_t nlen, plen, ipriv;
231 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 PyUnicode_READ_CHAR(ident, 0) != '_' ||
234 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_INCREF(ident);
236 return ident;
237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 nlen = PyUnicode_GET_LENGTH(ident);
239 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 The only time a name with a dot can occur is when
243 we are compiling an import statement that has a
244 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 TODO(jhylton): Decide whether we want to support
247 mangling of the module name, e.g. __M.X.
248 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
250 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
251 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(ident);
253 return ident; /* Don't mangle __whatever__ */
254 }
255 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 ipriv = 0;
257 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
258 ipriv++;
259 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 Py_INCREF(ident);
261 return ident; /* Don't mangle if class is just underscores */
262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000264
Antoine Pitrou55bff892013-04-06 21:21:04 +0200265 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
266 PyErr_SetString(PyExc_OverflowError,
267 "private identifier too large to be mangled");
268 return NULL;
269 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
272 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
273 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
274
275 result = PyUnicode_New(1 + nlen + plen, maxchar);
276 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200278 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
279 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200280 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
284 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
285 Py_DECREF(result);
286 return NULL;
287 }
Victor Stinner8f825062012-04-27 13:55:39 +0200288 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200289 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000290}
291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292static int
293compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296
INADA Naokic2e16072018-11-26 21:23:22 +0900297 c->c_const_cache = PyDict_New();
298 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900300 }
301
302 c->c_stack = PyList_New(0);
303 if (!c->c_stack) {
304 Py_CLEAR(c->c_const_cache);
305 return 0;
306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309}
310
311PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200312PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
313 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 struct compiler c;
316 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200317 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200319 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (!__doc__) {
322 __doc__ = PyUnicode_InternFromString("__doc__");
323 if (!__doc__)
324 return NULL;
325 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000326 if (!__annotations__) {
327 __annotations__ = PyUnicode_InternFromString("__annotations__");
328 if (!__annotations__)
329 return NULL;
330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (!compiler_init(&c))
332 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200333 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 c.c_filename = filename;
335 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (c.c_future == NULL)
338 goto finally;
339 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 flags = &local_flags;
341 }
342 merged = c.c_future->ff_features | flags->cf_flags;
343 c.c_future->ff_features = merged;
344 flags->cf_flags = merged;
345 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200346 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100348 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200350 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900351 goto finally;
352 }
353
Victor Stinner14e461d2013-08-26 22:28:21 +0200354 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (c.c_st == NULL) {
356 if (!PyErr_Occurred())
357 PyErr_SetString(PyExc_SystemError, "no symtable");
358 goto finally;
359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Thomas Wouters1175c432006-02-27 22:49:54 +0000363 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 compiler_free(&c);
365 assert(co || PyErr_Occurred());
366 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367}
368
369PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200370PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
371 int optimize, PyArena *arena)
372{
373 PyObject *filename;
374 PyCodeObject *co;
375 filename = PyUnicode_DecodeFSDefault(filename_str);
376 if (filename == NULL)
377 return NULL;
378 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
379 Py_DECREF(filename);
380 return co;
381
382}
383
384PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385PyNode_Compile(struct _node *n, const char *filename)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 PyCodeObject *co = NULL;
388 mod_ty mod;
389 PyArena *arena = PyArena_New();
390 if (!arena)
391 return NULL;
392 mod = PyAST_FromNode(n, NULL, filename, arena);
393 if (mod)
394 co = PyAST_Compile(mod, filename, NULL, arena);
395 PyArena_Free(arena);
396 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000397}
398
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000399static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (c->c_st)
403 PySymtable_Free(c->c_st);
404 if (c->c_future)
405 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200406 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900407 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000409}
410
Guido van Rossum79f25d91997-04-29 20:08:16 +0000411static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_ssize_t i, n;
415 PyObject *v, *k;
416 PyObject *dict = PyDict_New();
417 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 n = PyList_Size(list);
420 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100421 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (!v) {
423 Py_DECREF(dict);
424 return NULL;
425 }
426 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300427 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_DECREF(v);
429 Py_DECREF(dict);
430 return NULL;
431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_DECREF(v);
433 }
434 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435}
436
437/* Return new dict containing names from src that match scope(s).
438
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000439src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000441values are integers, starting at offset and increasing by one for
442each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443*/
444
445static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100446dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700448 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500450 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 assert(offset >= 0);
453 if (dest == NULL)
454 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455
Meador Inge2ca63152012-07-18 14:20:11 -0500456 /* Sort the keys so that we have a deterministic order on the indexes
457 saved in the returned dictionary. These indexes are used as indexes
458 into the free and cell var storage. Therefore if they aren't
459 deterministic, then the generated bytecode is not deterministic.
460 */
461 sorted_keys = PyDict_Keys(src);
462 if (sorted_keys == NULL)
463 return NULL;
464 if (PyList_Sort(sorted_keys) != 0) {
465 Py_DECREF(sorted_keys);
466 return NULL;
467 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500468 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500469
470 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* XXX this should probably be a macro in symtable.h */
472 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500473 k = PyList_GET_ITEM(sorted_keys, key_i);
474 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(PyLong_Check(v));
476 vi = PyLong_AS_LONG(v);
477 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500482 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_DECREF(dest);
484 return NULL;
485 }
486 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300487 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_DECREF(item);
490 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return NULL;
492 }
493 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 }
Meador Inge2ca63152012-07-18 14:20:11 -0500496 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000498}
499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500static void
501compiler_unit_check(struct compiler_unit *u)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 basicblock *block;
504 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700505 assert((uintptr_t)block != 0xcbcbcbcbU);
506 assert((uintptr_t)block != 0xfbfbfbfbU);
507 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (block->b_instr != NULL) {
509 assert(block->b_ialloc > 0);
510 assert(block->b_iused > 0);
511 assert(block->b_ialloc >= block->b_iused);
512 }
513 else {
514 assert (block->b_iused == 0);
515 assert (block->b_ialloc == 0);
516 }
517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static void
521compiler_unit_free(struct compiler_unit *u)
522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 compiler_unit_check(u);
526 b = u->u_blocks;
527 while (b != NULL) {
528 if (b->b_instr)
529 PyObject_Free((void *)b->b_instr);
530 next = b->b_list;
531 PyObject_Free((void *)b);
532 b = next;
533 }
534 Py_CLEAR(u->u_ste);
535 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400536 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_CLEAR(u->u_consts);
538 Py_CLEAR(u->u_names);
539 Py_CLEAR(u->u_varnames);
540 Py_CLEAR(u->u_freevars);
541 Py_CLEAR(u->u_cellvars);
542 Py_CLEAR(u->u_private);
543 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544}
545
546static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100547compiler_enter_scope(struct compiler *c, identifier name,
548 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100551 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
554 struct compiler_unit));
555 if (!u) {
556 PyErr_NoMemory();
557 return 0;
558 }
559 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100560 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100562 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 u->u_kwonlyargcount = 0;
564 u->u_ste = PySymtable_Lookup(c->c_st, key);
565 if (!u->u_ste) {
566 compiler_unit_free(u);
567 return 0;
568 }
569 Py_INCREF(name);
570 u->u_name = name;
571 u->u_varnames = list2dict(u->u_ste->ste_varnames);
572 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
573 if (!u->u_varnames || !u->u_cellvars) {
574 compiler_unit_free(u);
575 return 0;
576 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500577 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000578 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 int res;
582 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200583 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 name = _PyUnicode_FromId(&PyId___class__);
585 if (!name) {
586 compiler_unit_free(u);
587 return 0;
588 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300589 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 if (res < 0) {
591 compiler_unit_free(u);
592 return 0;
593 }
594 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200597 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (!u->u_freevars) {
599 compiler_unit_free(u);
600 return 0;
601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 u->u_blocks = NULL;
604 u->u_nfblocks = 0;
605 u->u_firstlineno = lineno;
606 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000607 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 u->u_lineno_set = 0;
609 u->u_consts = PyDict_New();
610 if (!u->u_consts) {
611 compiler_unit_free(u);
612 return 0;
613 }
614 u->u_names = PyDict_New();
615 if (!u->u_names) {
616 compiler_unit_free(u);
617 return 0;
618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Push the old compiler_unit on the stack. */
623 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400624 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
626 Py_XDECREF(capsule);
627 compiler_unit_free(u);
628 return 0;
629 }
630 Py_DECREF(capsule);
631 u->u_private = c->u->u_private;
632 Py_XINCREF(u->u_private);
633 }
634 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100637
638 block = compiler_new_block(c);
639 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100641 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400643 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
644 if (!compiler_set_qualname(c))
645 return 0;
646 }
647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000651static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652compiler_exit_scope(struct compiler *c)
653{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100654 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel--;
658 compiler_unit_free(c->u);
659 /* Restore c->u to the parent unit. */
660 n = PyList_GET_SIZE(c->c_stack) - 1;
661 if (n >= 0) {
662 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400663 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 assert(c->u);
665 /* we are deleting from a list so this really shouldn't fail */
666 if (PySequence_DelItem(c->c_stack, n) < 0)
667 Py_FatalError("compiler_exit_scope()");
668 compiler_unit_check(c->u);
669 }
670 else
671 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673}
674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675static int
676compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100678 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 _Py_static_string(dot_locals, ".<locals>");
680 Py_ssize_t stack_size;
681 struct compiler_unit *u = c->u;
682 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100685 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400686 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 if (stack_size > 1) {
688 int scope, force_global = 0;
689 struct compiler_unit *parent;
690 PyObject *mangled, *capsule;
691
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400692 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400693 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 assert(parent);
695
Yury Selivanov75445082015-05-11 22:57:16 -0400696 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
697 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
698 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 assert(u->u_name);
700 mangled = _Py_Mangle(parent->u_private, u->u_name);
701 if (!mangled)
702 return 0;
703 scope = PyST_GetScope(parent->u_ste, mangled);
704 Py_DECREF(mangled);
705 assert(scope != GLOBAL_IMPLICIT);
706 if (scope == GLOBAL_EXPLICIT)
707 force_global = 1;
708 }
709
710 if (!force_global) {
711 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400712 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400713 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
714 dot_locals_str = _PyUnicode_FromId(&dot_locals);
715 if (dot_locals_str == NULL)
716 return 0;
717 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
718 if (base == NULL)
719 return 0;
720 }
721 else {
722 Py_INCREF(parent->u_qualname);
723 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400724 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100725 }
726 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400728 if (base != NULL) {
729 dot_str = _PyUnicode_FromId(&dot);
730 if (dot_str == NULL) {
731 Py_DECREF(base);
732 return 0;
733 }
734 name = PyUnicode_Concat(base, dot_str);
735 Py_DECREF(base);
736 if (name == NULL)
737 return 0;
738 PyUnicode_Append(&name, u->u_name);
739 if (name == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(u->u_name);
744 name = u->u_name;
745 }
746 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100747
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400748 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100749}
750
Eric V. Smith235a6f02015-09-19 14:51:32 -0400751
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752/* Allocate a new block and return a pointer to it.
753 Returns NULL on error.
754*/
755
756static basicblock *
757compiler_new_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *b;
760 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 u = c->u;
763 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
764 if (b == NULL) {
765 PyErr_NoMemory();
766 return NULL;
767 }
768 memset((void *)b, 0, sizeof(basicblock));
769 /* Extend the singly linked list of blocks with new block. */
770 b->b_list = u->u_blocks;
771 u->u_blocks = b;
772 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773}
774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776compiler_next_block(struct compiler *c)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 basicblock *block = compiler_new_block(c);
779 if (block == NULL)
780 return NULL;
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786static basicblock *
787compiler_use_next_block(struct compiler *c, basicblock *block)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(block != NULL);
790 c->u->u_curblock->b_next = block;
791 c->u->u_curblock = block;
792 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
795/* Returns the offset of the next instruction in the current block's
796 b_instr array. Resizes the b_instr as necessary.
797 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000798*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799
800static int
801compiler_next_instr(struct compiler *c, basicblock *b)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 assert(b != NULL);
804 if (b->b_instr == NULL) {
805 b->b_instr = (struct instr *)PyObject_Malloc(
806 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
807 if (b->b_instr == NULL) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc = DEFAULT_BLOCK_SIZE;
812 memset((char *)b->b_instr, 0,
813 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
814 }
815 else if (b->b_iused == b->b_ialloc) {
816 struct instr *tmp;
817 size_t oldsize, newsize;
818 oldsize = b->b_ialloc * sizeof(struct instr);
819 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000820
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700821 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyErr_NoMemory();
823 return -1;
824 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (newsize == 0) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 b->b_ialloc <<= 1;
831 tmp = (struct instr *)PyObject_Realloc(
832 (void *)b->b_instr, newsize);
833 if (tmp == NULL) {
834 PyErr_NoMemory();
835 return -1;
836 }
837 b->b_instr = tmp;
838 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
839 }
840 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841}
842
Christian Heimes2202f872008-02-06 14:31:34 +0000843/* Set the i_lineno member of the instruction at offset off if the
844 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 already been set. If it has been set, the call has no effect.
846
Christian Heimes2202f872008-02-06 14:31:34 +0000847 The line number is reset in the following cases:
848 - when entering a new scope
849 - on each statement
850 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200851 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000852 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000853*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855static void
856compiler_set_lineno(struct compiler *c, int off)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 basicblock *b;
859 if (c->u->u_lineno_set)
860 return;
861 c->u->u_lineno_set = 1;
862 b = c->u->u_curblock;
863 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864}
865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866/* Return the stack effect of opcode with argument oparg.
867
868 Some opcodes have different stack effect when jump to the target and
869 when not jump. The 'jump' parameter specifies the case:
870
871 * 0 -- when not jump
872 * 1 -- when jump
873 * -1 -- maximal
874 */
875/* XXX Make the stack effect of WITH_CLEANUP_START and
876 WITH_CLEANUP_FINISH deterministic. */
877static int
878stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300881 case NOP:
882 case EXTENDED_ARG:
883 return 0;
884
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200885 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case POP_TOP:
887 return -1;
888 case ROT_TWO:
889 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200890 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return 0;
892 case DUP_TOP:
893 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000894 case DUP_TOP_TWO:
895 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200897 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case UNARY_POSITIVE:
899 case UNARY_NEGATIVE:
900 case UNARY_NOT:
901 case UNARY_INVERT:
902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case SET_ADD:
905 case LIST_APPEND:
906 return -1;
907 case MAP_ADD:
908 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000909
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200910 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_POWER:
912 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400913 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_MODULO:
915 case BINARY_ADD:
916 case BINARY_SUBTRACT:
917 case BINARY_SUBSCR:
918 case BINARY_FLOOR_DIVIDE:
919 case BINARY_TRUE_DIVIDE:
920 return -1;
921 case INPLACE_FLOOR_DIVIDE:
922 case INPLACE_TRUE_DIVIDE:
923 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_ADD:
926 case INPLACE_SUBTRACT:
927 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400928 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case INPLACE_MODULO:
930 return -1;
931 case STORE_SUBSCR:
932 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case DELETE_SUBSCR:
934 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case BINARY_LSHIFT:
937 case BINARY_RSHIFT:
938 case BINARY_AND:
939 case BINARY_XOR:
940 case BINARY_OR:
941 return -1;
942 case INPLACE_POWER:
943 return -1;
944 case GET_ITER:
945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case PRINT_EXPR:
948 return -1;
949 case LOAD_BUILD_CLASS:
950 return 1;
951 case INPLACE_LSHIFT:
952 case INPLACE_RSHIFT:
953 case INPLACE_AND:
954 case INPLACE_XOR:
955 case INPLACE_OR:
956 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 /* 1 in the normal flow.
960 * Restore the stack position and push 6 values before jumping to
961 * the handler if an exception be raised. */
962 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400963 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400965 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* Pop a variable number of values pushed by WITH_CLEANUP_START
967 * + __exit__ or __aexit__. */
968 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case RETURN_VALUE:
970 return -1;
971 case IMPORT_STAR:
972 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700973 case SETUP_ANNOTATIONS:
974 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case YIELD_VALUE:
976 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500977 case YIELD_FROM:
978 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case POP_BLOCK:
980 return 0;
981 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200982 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200984 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200985 /* Pop 6 values when an exception was raised. */
986 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case STORE_NAME:
989 return -1;
990 case DELETE_NAME:
991 return 0;
992 case UNPACK_SEQUENCE:
993 return oparg-1;
994 case UNPACK_EX:
995 return (oparg&0xFF) + (oparg>>8);
996 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200997 /* -1 at end of iterator, 1 if continue iterating. */
998 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case STORE_ATTR:
1001 return -2;
1002 case DELETE_ATTR:
1003 return -1;
1004 case STORE_GLOBAL:
1005 return -1;
1006 case DELETE_GLOBAL:
1007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_CONST:
1009 return 1;
1010 case LOAD_NAME:
1011 return 1;
1012 case BUILD_TUPLE:
1013 case BUILD_LIST:
1014 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001015 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001017 case BUILD_LIST_UNPACK:
1018 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001019 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001020 case BUILD_SET_UNPACK:
1021 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001022 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001023 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001025 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001026 case BUILD_CONST_KEY_MAP:
1027 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_ATTR:
1029 return 0;
1030 case COMPARE_OP:
1031 return -1;
1032 case IMPORT_NAME:
1033 return -1;
1034 case IMPORT_FROM:
1035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case JUMP_ABSOLUTE:
1040 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001042 case JUMP_IF_TRUE_OR_POP:
1043 case JUMP_IF_FALSE_OR_POP:
1044 return jump ? 0 : -1;
1045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case POP_JUMP_IF_FALSE:
1047 case POP_JUMP_IF_TRUE:
1048 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case LOAD_GLOBAL:
1051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001053 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001055 /* 0 in the normal flow.
1056 * Restore the stack position and push 6 values before jumping to
1057 * the handler if an exception be raised. */
1058 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001059 case BEGIN_FINALLY:
1060 /* Actually pushes 1 value, but count 6 for balancing with
1061 * END_FINALLY and POP_FINALLY.
1062 * This is the main reason of using this opcode instead of
1063 * "LOAD_CONST None". */
1064 return 6;
1065 case CALL_FINALLY:
1066 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case LOAD_FAST:
1069 return 1;
1070 case STORE_FAST:
1071 return -1;
1072 case DELETE_FAST:
1073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case RAISE_VARARGS:
1076 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001077
1078 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001080 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001081 case CALL_METHOD:
1082 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001084 return -oparg-1;
1085 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001086 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001087 case MAKE_FUNCTION:
1088 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1089 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 case BUILD_SLICE:
1091 if (oparg == 3)
1092 return -2;
1093 else
1094 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case LOAD_CLOSURE:
1098 return 1;
1099 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001100 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return 1;
1102 case STORE_DEREF:
1103 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001104 case DELETE_DEREF:
1105 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001106
1107 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case GET_AWAITABLE:
1109 return 0;
1110 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001111 /* 0 in the normal flow.
1112 * Restore the stack position to the position before the result
1113 * of __aenter__ and push 6 values before jumping to the handler
1114 * if an exception be raised. */
1115 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case BEFORE_ASYNC_WITH:
1117 return 1;
1118 case GET_AITER:
1119 return 0;
1120 case GET_ANEXT:
1121 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001122 case GET_YIELD_FROM_ITER:
1123 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001124 case END_ASYNC_FOR:
1125 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001126 case FORMAT_VALUE:
1127 /* If there's a fmt_spec on the stack, we go from 2->1,
1128 else 1->1. */
1129 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001130 case LOAD_METHOD:
1131 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001132 case LOAD_ASSERTION_ERROR:
1133 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001135 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Larry Hastings3a907972013-11-23 14:49:22 -08001137 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138}
1139
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001140int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001141PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1142{
1143 return stack_effect(opcode, oparg, jump);
1144}
1145
1146int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001147PyCompile_OpcodeStackEffect(int opcode, int oparg)
1148{
1149 return stack_effect(opcode, oparg, -1);
1150}
1151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152/* Add an opcode with no argument.
1153 Returns 0 on failure, 1 on success.
1154*/
1155
1156static int
1157compiler_addop(struct compiler *c, int opcode)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 basicblock *b;
1160 struct instr *i;
1161 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001162 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001163 if (c->c_do_not_emit_bytecode) {
1164 return 1;
1165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 off = compiler_next_instr(c, c->u->u_curblock);
1167 if (off < 0)
1168 return 0;
1169 b = c->u->u_curblock;
1170 i = &b->b_instr[off];
1171 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001172 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (opcode == RETURN_VALUE)
1174 b->b_return = 1;
1175 compiler_set_lineno(c, off);
1176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177}
1178
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1181{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001185 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001187 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001189 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001190 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 return -1;
1194 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001195 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_DECREF(v);
1197 return -1;
1198 }
1199 Py_DECREF(v);
1200 }
1201 else
1202 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 return arg;
1204}
1205
INADA Naokic2e16072018-11-26 21:23:22 +09001206// Merge const *o* recursively and return constant key object.
1207static PyObject*
1208merge_consts_recursive(struct compiler *c, PyObject *o)
1209{
1210 // None and Ellipsis are singleton, and key is the singleton.
1211 // No need to merge object and key.
1212 if (o == Py_None || o == Py_Ellipsis) {
1213 Py_INCREF(o);
1214 return o;
1215 }
1216
1217 PyObject *key = _PyCode_ConstantKey(o);
1218 if (key == NULL) {
1219 return NULL;
1220 }
1221
1222 // t is borrowed reference
1223 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1224 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001226 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001227 Py_DECREF(key);
1228 return t;
1229 }
1230
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001232 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001234 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001235 Py_ssize_t len = PyTuple_GET_SIZE(o);
1236 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001237 PyObject *item = PyTuple_GET_ITEM(o, i);
1238 PyObject *u = merge_consts_recursive(c, item);
1239 if (u == NULL) {
1240 Py_DECREF(key);
1241 return NULL;
1242 }
1243
1244 // See _PyCode_ConstantKey()
1245 PyObject *v; // borrowed
1246 if (PyTuple_CheckExact(u)) {
1247 v = PyTuple_GET_ITEM(u, 1);
1248 }
1249 else {
1250 v = u;
1251 }
1252 if (v != item) {
1253 Py_INCREF(v);
1254 PyTuple_SET_ITEM(o, i, v);
1255 Py_DECREF(item);
1256 }
1257
1258 Py_DECREF(u);
1259 }
1260 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001262 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001263 // constant keys.
1264 // See _PyCode_ConstantKey() for detail.
1265 assert(PyTuple_CheckExact(key));
1266 assert(PyTuple_GET_SIZE(key) == 2);
1267
1268 Py_ssize_t len = PySet_GET_SIZE(o);
1269 if (len == 0) { // empty frozenset should not be re-created.
1270 return key;
1271 }
1272 PyObject *tuple = PyTuple_New(len);
1273 if (tuple == NULL) {
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 Py_ssize_t i = 0, pos = 0;
1278 PyObject *item;
1279 Py_hash_t hash;
1280 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1281 PyObject *k = merge_consts_recursive(c, item);
1282 if (k == NULL) {
1283 Py_DECREF(tuple);
1284 Py_DECREF(key);
1285 return NULL;
1286 }
1287 PyObject *u;
1288 if (PyTuple_CheckExact(k)) {
1289 u = PyTuple_GET_ITEM(k, 1);
1290 Py_INCREF(u);
1291 Py_DECREF(k);
1292 }
1293 else {
1294 u = k;
1295 }
1296 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1297 i++;
1298 }
1299
1300 // Instead of rewriting o, we create new frozenset and embed in the
1301 // key tuple. Caller should get merged frozenset from the key tuple.
1302 PyObject *new = PyFrozenSet_New(tuple);
1303 Py_DECREF(tuple);
1304 if (new == NULL) {
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 assert(PyTuple_GET_ITEM(key, 1) == o);
1309 Py_DECREF(o);
1310 PyTuple_SET_ITEM(key, 1, new);
1311 }
INADA Naokic2e16072018-11-26 21:23:22 +09001312
1313 return key;
1314}
1315
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316static Py_ssize_t
1317compiler_add_const(struct compiler *c, PyObject *o)
1318{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001319 if (c->c_do_not_emit_bytecode) {
1320 return 0;
1321 }
1322
INADA Naokic2e16072018-11-26 21:23:22 +09001323 PyObject *key = merge_consts_recursive(c, o);
1324 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001326 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001327
INADA Naokic2e16072018-11-26 21:23:22 +09001328 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1329 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
1333static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001334compiler_addop_load_const(struct compiler *c, PyObject *o)
1335{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001336 if (c->c_do_not_emit_bytecode) {
1337 return 1;
1338 }
1339
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001340 Py_ssize_t arg = compiler_add_const(c, o);
1341 if (arg < 0)
1342 return 0;
1343 return compiler_addop_i(c, LOAD_CONST, arg);
1344}
1345
1346static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001350 if (c->c_do_not_emit_bytecode) {
1351 return 1;
1352 }
1353
Victor Stinnerad9a0662013-11-19 22:23:20 +01001354 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 return compiler_addop_i(c, opcode, arg);
1358}
1359
1360static int
1361compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001364 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001365
1366 if (c->c_do_not_emit_bytecode) {
1367 return 1;
1368 }
1369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1371 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001372 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 arg = compiler_add_o(c, dict, mangled);
1374 Py_DECREF(mangled);
1375 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001376 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 return compiler_addop_i(c, opcode, arg);
1378}
1379
1380/* Add an opcode with an integer argument.
1381 Returns 0 on failure, 1 on success.
1382*/
1383
1384static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001385compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 struct instr *i;
1388 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001389
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001390 if (c->c_do_not_emit_bytecode) {
1391 return 1;
1392 }
1393
Victor Stinner2ad474b2016-03-01 23:34:47 +01001394 /* oparg value is unsigned, but a signed C int is usually used to store
1395 it in the C code (like Python/ceval.c).
1396
1397 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1398
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001399 The argument of a concrete bytecode instruction is limited to 8-bit.
1400 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1401 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001402 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 off = compiler_next_instr(c, c->u->u_curblock);
1405 if (off < 0)
1406 return 0;
1407 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001408 i->i_opcode = opcode;
1409 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 compiler_set_lineno(c, off);
1411 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412}
1413
1414static int
1415compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 struct instr *i;
1418 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001420 if (c->c_do_not_emit_bytecode) {
1421 return 1;
1422 }
1423
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001424 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(b != NULL);
1426 off = compiler_next_instr(c, c->u->u_curblock);
1427 if (off < 0)
1428 return 0;
1429 i = &c->u->u_curblock->b_instr[off];
1430 i->i_opcode = opcode;
1431 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (absolute)
1433 i->i_jabs = 1;
1434 else
1435 i->i_jrel = 1;
1436 compiler_set_lineno(c, off);
1437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438}
1439
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001440/* NEXT_BLOCK() creates an implicit jump from the current block
1441 to the new block.
1442
1443 The returns inside this macro make it impossible to decref objects
1444 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (compiler_next_block((C)) == NULL) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
1451#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) \
1453 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454}
1455
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop((C), (OP))) { \
1458 compiler_exit_scope(c); \
1459 return 0; \
1460 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001461}
1462
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001463#define ADDOP_LOAD_CONST(C, O) { \
1464 if (!compiler_addop_load_const((C), (O))) \
1465 return 0; \
1466}
1467
1468/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1469#define ADDOP_LOAD_CONST_NEW(C, O) { \
1470 PyObject *__new_const = (O); \
1471 if (__new_const == NULL) { \
1472 return 0; \
1473 } \
1474 if (!compiler_addop_load_const((C), __new_const)) { \
1475 Py_DECREF(__new_const); \
1476 return 0; \
1477 } \
1478 Py_DECREF(__new_const); \
1479}
1480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1483 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484}
1485
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001486/* Same as ADDOP_O, but steals a reference. */
1487#define ADDOP_N(C, OP, O, TYPE) { \
1488 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1489 Py_DECREF((O)); \
1490 return 0; \
1491 } \
1492 Py_DECREF((O)); \
1493}
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_i((C), (OP), (O))) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_addop_j((C), (OP), (O), 1)) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
1510#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!compiler_addop_j((C), (OP), (O), 0)) \
1512 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513}
1514
1515/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1516 the ASDL name to synthesize the name of the C type and the visit function.
1517*/
1518
1519#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) \
1521 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522}
1523
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_visit_ ## TYPE((C), (V))) { \
1526 compiler_exit_scope(c); \
1527 return 0; \
1528 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001529}
1530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (!compiler_visit_slice((C), (V), (CTX))) \
1533 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int _i; \
1538 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1539 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1540 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1541 if (!compiler_visit_ ## TYPE((C), elt)) \
1542 return 0; \
1543 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544}
1545
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int _i; \
1548 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1549 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1550 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1551 if (!compiler_visit_ ## TYPE((C), elt)) { \
1552 compiler_exit_scope(c); \
1553 return 0; \
1554 } \
1555 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001556}
1557
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001558/* These macros allows to check only for errors and not emmit bytecode
1559 * while visiting nodes.
1560*/
1561
1562#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1563 c->c_do_not_emit_bytecode++;
1564
1565#define END_DO_NOT_EMIT_BYTECODE \
1566 c->c_do_not_emit_bytecode--; \
1567}
1568
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001569/* Search if variable annotations are present statically in a block. */
1570
1571static int
1572find_ann(asdl_seq *stmts)
1573{
1574 int i, j, res = 0;
1575 stmt_ty st;
1576
1577 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1578 st = (stmt_ty)asdl_seq_GET(stmts, i);
1579 switch (st->kind) {
1580 case AnnAssign_kind:
1581 return 1;
1582 case For_kind:
1583 res = find_ann(st->v.For.body) ||
1584 find_ann(st->v.For.orelse);
1585 break;
1586 case AsyncFor_kind:
1587 res = find_ann(st->v.AsyncFor.body) ||
1588 find_ann(st->v.AsyncFor.orelse);
1589 break;
1590 case While_kind:
1591 res = find_ann(st->v.While.body) ||
1592 find_ann(st->v.While.orelse);
1593 break;
1594 case If_kind:
1595 res = find_ann(st->v.If.body) ||
1596 find_ann(st->v.If.orelse);
1597 break;
1598 case With_kind:
1599 res = find_ann(st->v.With.body);
1600 break;
1601 case AsyncWith_kind:
1602 res = find_ann(st->v.AsyncWith.body);
1603 break;
1604 case Try_kind:
1605 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1606 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1607 st->v.Try.handlers, j);
1608 if (find_ann(handler->v.ExceptHandler.body)) {
1609 return 1;
1610 }
1611 }
1612 res = find_ann(st->v.Try.body) ||
1613 find_ann(st->v.Try.finalbody) ||
1614 find_ann(st->v.Try.orelse);
1615 break;
1616 default:
1617 res = 0;
1618 }
1619 if (res) {
1620 break;
1621 }
1622 }
1623 return res;
1624}
1625
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001626/*
1627 * Frame block handling functions
1628 */
1629
1630static int
1631compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1632 basicblock *exit)
1633{
1634 struct fblockinfo *f;
1635 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1636 PyErr_SetString(PyExc_SyntaxError,
1637 "too many statically nested blocks");
1638 return 0;
1639 }
1640 f = &c->u->u_fblock[c->u->u_nfblocks++];
1641 f->fb_type = t;
1642 f->fb_block = b;
1643 f->fb_exit = exit;
1644 return 1;
1645}
1646
1647static void
1648compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1649{
1650 struct compiler_unit *u = c->u;
1651 assert(u->u_nfblocks > 0);
1652 u->u_nfblocks--;
1653 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1654 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1655}
1656
1657/* Unwind a frame block. If preserve_tos is true, the TOS before
1658 * popping the blocks will be restored afterwards.
1659 */
1660static int
1661compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1662 int preserve_tos)
1663{
1664 switch (info->fb_type) {
1665 case WHILE_LOOP:
1666 return 1;
1667
1668 case FINALLY_END:
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001669 info->fb_exit = NULL;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001670 ADDOP_I(c, POP_FINALLY, preserve_tos);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001671 if (preserve_tos) {
1672 ADDOP(c, ROT_TWO);
1673 }
1674 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001675 return 1;
1676
1677 case FOR_LOOP:
1678 /* Pop the iterator */
1679 if (preserve_tos) {
1680 ADDOP(c, ROT_TWO);
1681 }
1682 ADDOP(c, POP_TOP);
1683 return 1;
1684
1685 case EXCEPT:
1686 ADDOP(c, POP_BLOCK);
1687 return 1;
1688
1689 case FINALLY_TRY:
1690 ADDOP(c, POP_BLOCK);
1691 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1692 return 1;
1693
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001694 case FINALLY_TRY2:
1695 ADDOP(c, POP_BLOCK);
1696 if (preserve_tos) {
1697 ADDOP(c, ROT_TWO);
1698 ADDOP(c, POP_TOP);
1699 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1700 }
1701 else {
1702 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1703 ADDOP(c, POP_TOP);
1704 }
1705 return 1;
1706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 case WITH:
1708 case ASYNC_WITH:
1709 ADDOP(c, POP_BLOCK);
1710 if (preserve_tos) {
1711 ADDOP(c, ROT_TWO);
1712 }
1713 ADDOP(c, BEGIN_FINALLY);
1714 ADDOP(c, WITH_CLEANUP_START);
1715 if (info->fb_type == ASYNC_WITH) {
1716 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001717 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001718 ADDOP(c, YIELD_FROM);
1719 }
1720 ADDOP(c, WITH_CLEANUP_FINISH);
1721 ADDOP_I(c, POP_FINALLY, 0);
1722 return 1;
1723
1724 case HANDLER_CLEANUP:
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_FOUR);
1727 }
1728 if (info->fb_exit) {
1729 ADDOP(c, POP_BLOCK);
1730 ADDOP(c, POP_EXCEPT);
1731 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1732 }
1733 else {
1734 ADDOP(c, POP_EXCEPT);
1735 }
1736 return 1;
1737 }
1738 Py_UNREACHABLE();
1739}
1740
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001741/* Compile a sequence of statements, checking for a docstring
1742 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743
1744static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001745compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001746{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001747 int i = 0;
1748 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001749 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001750
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001751 /* Set current line number to the line number of first statement.
1752 This way line number for SETUP_ANNOTATIONS will always
1753 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301754 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001755 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1756 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001757 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001758 c->u->u_lineno = st->lineno;
1759 }
1760 /* Every annotated class and module should have __annotations__. */
1761 if (find_ann(stmts)) {
1762 ADDOP(c, SETUP_ANNOTATIONS);
1763 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001764 if (!asdl_seq_LEN(stmts))
1765 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001766 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001767 if (c->c_optimize < 2) {
1768 docstring = _PyAST_GetDocString(stmts);
1769 if (docstring) {
1770 i = 1;
1771 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1772 assert(st->kind == Expr_kind);
1773 VISIT(c, expr, st->v.Expr.value);
1774 if (!compiler_nameop(c, __doc__, Store))
1775 return 0;
1776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001778 for (; i < asdl_seq_LEN(stmts); i++)
1779 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781}
1782
1783static PyCodeObject *
1784compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCodeObject *co;
1787 int addNone = 1;
1788 static PyObject *module;
1789 if (!module) {
1790 module = PyUnicode_InternFromString("<module>");
1791 if (!module)
1792 return NULL;
1793 }
1794 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001795 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return NULL;
1797 switch (mod->kind) {
1798 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001799 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 compiler_exit_scope(c);
1801 return 0;
1802 }
1803 break;
1804 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001805 if (find_ann(mod->v.Interactive.body)) {
1806 ADDOP(c, SETUP_ANNOTATIONS);
1807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 c->c_interactive = 1;
1809 VISIT_SEQ_IN_SCOPE(c, stmt,
1810 mod->v.Interactive.body);
1811 break;
1812 case Expression_kind:
1813 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1814 addNone = 0;
1815 break;
1816 case Suite_kind:
1817 PyErr_SetString(PyExc_SystemError,
1818 "suite should not be possible");
1819 return 0;
1820 default:
1821 PyErr_Format(PyExc_SystemError,
1822 "module kind %d should not be possible",
1823 mod->kind);
1824 return 0;
1825 }
1826 co = assemble(c, addNone);
1827 compiler_exit_scope(c);
1828 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001829}
1830
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831/* The test for LOCAL must come before the test for FREE in order to
1832 handle classes where name is both local and free. The local var is
1833 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001834*/
1835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836static int
1837get_ref_type(struct compiler *c, PyObject *name)
1838{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001839 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001840 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001841 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001842 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001843 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (scope == 0) {
1845 char buf[350];
1846 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001847 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001849 PyUnicode_AsUTF8(name),
1850 PyUnicode_AsUTF8(c->u->u_name),
1851 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1852 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1853 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1854 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 );
1856 Py_FatalError(buf);
1857 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860}
1861
1862static int
1863compiler_lookup_arg(PyObject *dict, PyObject *name)
1864{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001865 PyObject *v;
1866 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001868 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001869 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870}
1871
1872static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001873compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001875 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001876 if (qualname == NULL)
1877 qualname = co->co_name;
1878
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001879 if (free) {
1880 for (i = 0; i < free; ++i) {
1881 /* Bypass com_addop_varname because it will generate
1882 LOAD_DEREF but LOAD_CLOSURE is needed.
1883 */
1884 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1885 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001887 /* Special case: If a class contains a method with a
1888 free variable that has the same name as a method,
1889 the name will be considered free *and* local in the
1890 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001891 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001892 */
1893 reftype = get_ref_type(c, name);
1894 if (reftype == CELL)
1895 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1896 else /* (reftype == FREE) */
1897 arg = compiler_lookup_arg(c->u->u_freevars, name);
1898 if (arg == -1) {
1899 fprintf(stderr,
1900 "lookup %s in %s %d %d\n"
1901 "freevars of %s: %s\n",
1902 PyUnicode_AsUTF8(PyObject_Repr(name)),
1903 PyUnicode_AsUTF8(c->u->u_name),
1904 reftype, arg,
1905 PyUnicode_AsUTF8(co->co_name),
1906 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1907 Py_FatalError("compiler_make_closure()");
1908 }
1909 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 flags |= 0x08;
1912 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 ADDOP_LOAD_CONST(c, (PyObject*)co);
1915 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918}
1919
1920static int
1921compiler_decorators(struct compiler *c, asdl_seq* decos)
1922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (!decos)
1926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1929 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1930 }
1931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
1934static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001935compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001937{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001938 /* Push a dict of keyword-only default values.
1939
1940 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1941 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001942 int i;
1943 PyObject *keys = NULL;
1944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1946 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1947 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1948 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001949 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001950 if (!mangled) {
1951 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 if (keys == NULL) {
1954 keys = PyList_New(1);
1955 if (keys == NULL) {
1956 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001957 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001958 }
1959 PyList_SET_ITEM(keys, 0, mangled);
1960 }
1961 else {
1962 int res = PyList_Append(keys, mangled);
1963 Py_DECREF(mangled);
1964 if (res == -1) {
1965 goto error;
1966 }
1967 }
1968 if (!compiler_visit_expr(c, default_)) {
1969 goto error;
1970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 }
1972 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001973 if (keys != NULL) {
1974 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1975 PyObject *keys_tuple = PyList_AsTuple(keys);
1976 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001977 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001978 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001979 assert(default_count > 0);
1980 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001981 }
1982 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001983 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001984 }
1985
1986error:
1987 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001988 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001989}
1990
1991static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001992compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1993{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001994 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001995 return 1;
1996}
1997
1998static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001999compiler_visit_argannotation(struct compiler *c, identifier id,
2000 expr_ty annotation, PyObject *names)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002003 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002004 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2005 VISIT(c, annexpr, annotation)
2006 }
2007 else {
2008 VISIT(c, expr, annotation);
2009 }
Victor Stinner065efc32014-02-18 22:07:56 +01002010 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002011 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002012 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002013 if (PyList_Append(names, mangled) < 0) {
2014 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002015 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002016 }
2017 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002019 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002020}
2021
2022static int
2023compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2024 PyObject *names)
2025{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002026 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 for (i = 0; i < asdl_seq_LEN(args); i++) {
2028 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002029 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 c,
2031 arg->arg,
2032 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002033 names))
2034 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002036 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002037}
2038
2039static int
2040compiler_visit_annotations(struct compiler *c, arguments_ty args,
2041 expr_ty returns)
2042{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002043 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002044 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002045
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002046 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 */
2048 static identifier return_str;
2049 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002050 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 names = PyList_New(0);
2052 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002053 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002054
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002055 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002057 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2058 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002059 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002061 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002065 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002067 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (!return_str) {
2071 return_str = PyUnicode_InternFromString("return");
2072 if (!return_str)
2073 goto error;
2074 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 goto error;
2077 }
2078
2079 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002081 PyObject *keytuple = PyList_AsTuple(names);
2082 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002083 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002084 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002085 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002087 else {
2088 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002089 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002090 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002091
2092error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002094 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002095}
2096
2097static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002098compiler_visit_defaults(struct compiler *c, arguments_ty args)
2099{
2100 VISIT_SEQ(c, expr, args->defaults);
2101 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2102 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103}
2104
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105static Py_ssize_t
2106compiler_default_arguments(struct compiler *c, arguments_ty args)
2107{
2108 Py_ssize_t funcflags = 0;
2109 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110 if (!compiler_visit_defaults(c, args))
2111 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 funcflags |= 0x01;
2113 }
2114 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002115 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002117 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 return -1;
2119 }
2120 else if (res > 0) {
2121 funcflags |= 0x02;
2122 }
2123 }
2124 return funcflags;
2125}
2126
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127static int
Yury Selivanov75445082015-05-11 22:57:16 -04002128compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002131 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002132 arguments_ty args;
2133 expr_ty returns;
2134 identifier name;
2135 asdl_seq* decos;
2136 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002137 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002139 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002140 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
Yury Selivanov75445082015-05-11 22:57:16 -04002142 if (is_async) {
2143 assert(s->kind == AsyncFunctionDef_kind);
2144
2145 args = s->v.AsyncFunctionDef.args;
2146 returns = s->v.AsyncFunctionDef.returns;
2147 decos = s->v.AsyncFunctionDef.decorator_list;
2148 name = s->v.AsyncFunctionDef.name;
2149 body = s->v.AsyncFunctionDef.body;
2150
2151 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2152 } else {
2153 assert(s->kind == FunctionDef_kind);
2154
2155 args = s->v.FunctionDef.args;
2156 returns = s->v.FunctionDef.returns;
2157 decos = s->v.FunctionDef.decorator_list;
2158 name = s->v.FunctionDef.name;
2159 body = s->v.FunctionDef.body;
2160
2161 scope_type = COMPILER_SCOPE_FUNCTION;
2162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (!compiler_decorators(c, decos))
2165 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002166
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002167 firstlineno = s->lineno;
2168 if (asdl_seq_LEN(decos)) {
2169 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2170 }
2171
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002172 funcflags = compiler_default_arguments(c, args);
2173 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002175 }
2176
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002177 annotations = compiler_visit_annotations(c, args, returns);
2178 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002179 return 0;
2180 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002181 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002182 funcflags |= 0x04;
2183 }
2184
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002185 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002186 return 0;
2187 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188
INADA Naokicb41b272017-02-23 00:31:59 +09002189 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002190 if (c->c_optimize < 2) {
2191 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002192 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002193 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 compiler_exit_scope(c);
2195 return 0;
2196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002199 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002201 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002203 qualname = c->u->u_qualname;
2204 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002206 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002207 Py_XDECREF(qualname);
2208 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002212 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002213 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* decorators */
2217 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2218 ADDOP_I(c, CALL_FUNCTION, 1);
2219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220
Yury Selivanov75445082015-05-11 22:57:16 -04002221 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222}
2223
2224static int
2225compiler_class(struct compiler *c, stmt_ty s)
2226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyCodeObject *co;
2228 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002229 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (!compiler_decorators(c, decos))
2233 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002234
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002235 firstlineno = s->lineno;
2236 if (asdl_seq_LEN(decos)) {
2237 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2238 }
2239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* ultimately generate code for:
2241 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2242 where:
2243 <func> is a function/closure created from the class body;
2244 it has a single argument (__locals__) where the dict
2245 (or MutableSequence) representing the locals is passed
2246 <name> is the class name
2247 <bases> is the positional arguments and *varargs argument
2248 <keywords> is the keyword arguments and **kwds argument
2249 This borrows from compiler_call.
2250 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002253 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002254 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 return 0;
2256 /* this block represents what we do in the new scope */
2257 {
2258 /* use the class name for name mangling */
2259 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002260 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* load (global) __name__ ... */
2262 str = PyUnicode_InternFromString("__name__");
2263 if (!str || !compiler_nameop(c, str, Load)) {
2264 Py_XDECREF(str);
2265 compiler_exit_scope(c);
2266 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Py_DECREF(str);
2269 /* ... and store it as __module__ */
2270 str = PyUnicode_InternFromString("__module__");
2271 if (!str || !compiler_nameop(c, str, Store)) {
2272 Py_XDECREF(str);
2273 compiler_exit_scope(c);
2274 return 0;
2275 }
2276 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002277 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002278 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002279 str = PyUnicode_InternFromString("__qualname__");
2280 if (!str || !compiler_nameop(c, str, Store)) {
2281 Py_XDECREF(str);
2282 compiler_exit_scope(c);
2283 return 0;
2284 }
2285 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002287 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 compiler_exit_scope(c);
2289 return 0;
2290 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002291 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002292 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002293 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002294 str = PyUnicode_InternFromString("__class__");
2295 if (str == NULL) {
2296 compiler_exit_scope(c);
2297 return 0;
2298 }
2299 i = compiler_lookup_arg(c->u->u_cellvars, str);
2300 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002301 if (i < 0) {
2302 compiler_exit_scope(c);
2303 return 0;
2304 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002305 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002308 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002309 str = PyUnicode_InternFromString("__classcell__");
2310 if (!str || !compiler_nameop(c, str, Store)) {
2311 Py_XDECREF(str);
2312 compiler_exit_scope(c);
2313 return 0;
2314 }
2315 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002317 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002318 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002319 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002320 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002321 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002322 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* create the code object */
2324 co = assemble(c, 1);
2325 }
2326 /* leave the new scope */
2327 compiler_exit_scope(c);
2328 if (co == NULL)
2329 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* 2. load the 'build_class' function */
2332 ADDOP(c, LOAD_BUILD_CLASS);
2333
2334 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002335 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 Py_DECREF(co);
2337
2338 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002339 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340
2341 /* 5. generate the rest of the code for the call */
2342 if (!compiler_call_helper(c, 2,
2343 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002344 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return 0;
2346
2347 /* 6. apply decorators */
2348 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2349 ADDOP_I(c, CALL_FUNCTION, 1);
2350 }
2351
2352 /* 7. store into <name> */
2353 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2354 return 0;
2355 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356}
2357
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002358/* Return 0 if the expression is a constant value except named singletons.
2359 Return 1 otherwise. */
2360static int
2361check_is_arg(expr_ty e)
2362{
2363 if (e->kind != Constant_kind) {
2364 return 1;
2365 }
2366 PyObject *value = e->v.Constant.value;
2367 return (value == Py_None
2368 || value == Py_False
2369 || value == Py_True
2370 || value == Py_Ellipsis);
2371}
2372
2373/* Check operands of identity chacks ("is" and "is not").
2374 Emit a warning if any operand is a constant except named singletons.
2375 Return 0 on error.
2376 */
2377static int
2378check_compare(struct compiler *c, expr_ty e)
2379{
2380 Py_ssize_t i, n;
2381 int left = check_is_arg(e->v.Compare.left);
2382 n = asdl_seq_LEN(e->v.Compare.ops);
2383 for (i = 0; i < n; i++) {
2384 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2385 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2386 if (op == Is || op == IsNot) {
2387 if (!right || !left) {
2388 const char *msg = (op == Is)
2389 ? "\"is\" with a literal. Did you mean \"==\"?"
2390 : "\"is not\" with a literal. Did you mean \"!=\"?";
2391 return compiler_warn(c, msg);
2392 }
2393 }
2394 left = right;
2395 }
2396 return 1;
2397}
2398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002400cmpop(cmpop_ty op)
2401{
2402 switch (op) {
2403 case Eq:
2404 return PyCmp_EQ;
2405 case NotEq:
2406 return PyCmp_NE;
2407 case Lt:
2408 return PyCmp_LT;
2409 case LtE:
2410 return PyCmp_LE;
2411 case Gt:
2412 return PyCmp_GT;
2413 case GtE:
2414 return PyCmp_GE;
2415 case Is:
2416 return PyCmp_IS;
2417 case IsNot:
2418 return PyCmp_IS_NOT;
2419 case In:
2420 return PyCmp_IN;
2421 case NotIn:
2422 return PyCmp_NOT_IN;
2423 default:
2424 return PyCmp_BAD;
2425 }
2426}
2427
2428static int
2429compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2430{
2431 switch (e->kind) {
2432 case UnaryOp_kind:
2433 if (e->v.UnaryOp.op == Not)
2434 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2435 /* fallback to general implementation */
2436 break;
2437 case BoolOp_kind: {
2438 asdl_seq *s = e->v.BoolOp.values;
2439 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2440 assert(n >= 0);
2441 int cond2 = e->v.BoolOp.op == Or;
2442 basicblock *next2 = next;
2443 if (!cond2 != !cond) {
2444 next2 = compiler_new_block(c);
2445 if (next2 == NULL)
2446 return 0;
2447 }
2448 for (i = 0; i < n; ++i) {
2449 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2450 return 0;
2451 }
2452 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2453 return 0;
2454 if (next2 != next)
2455 compiler_use_next_block(c, next2);
2456 return 1;
2457 }
2458 case IfExp_kind: {
2459 basicblock *end, *next2;
2460 end = compiler_new_block(c);
2461 if (end == NULL)
2462 return 0;
2463 next2 = compiler_new_block(c);
2464 if (next2 == NULL)
2465 return 0;
2466 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2467 return 0;
2468 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2469 return 0;
2470 ADDOP_JREL(c, JUMP_FORWARD, end);
2471 compiler_use_next_block(c, next2);
2472 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2473 return 0;
2474 compiler_use_next_block(c, end);
2475 return 1;
2476 }
2477 case Compare_kind: {
2478 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2479 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002480 if (!check_compare(c, e)) {
2481 return 0;
2482 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 basicblock *cleanup = compiler_new_block(c);
2484 if (cleanup == NULL)
2485 return 0;
2486 VISIT(c, expr, e->v.Compare.left);
2487 for (i = 0; i < n; i++) {
2488 VISIT(c, expr,
2489 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2490 ADDOP(c, DUP_TOP);
2491 ADDOP(c, ROT_THREE);
2492 ADDOP_I(c, COMPARE_OP,
2493 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2494 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2495 NEXT_BLOCK(c);
2496 }
2497 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2498 ADDOP_I(c, COMPARE_OP,
2499 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2500 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2501 basicblock *end = compiler_new_block(c);
2502 if (end == NULL)
2503 return 0;
2504 ADDOP_JREL(c, JUMP_FORWARD, end);
2505 compiler_use_next_block(c, cleanup);
2506 ADDOP(c, POP_TOP);
2507 if (!cond) {
2508 ADDOP_JREL(c, JUMP_FORWARD, next);
2509 }
2510 compiler_use_next_block(c, end);
2511 return 1;
2512 }
2513 /* fallback to general implementation */
2514 break;
2515 }
2516 default:
2517 /* fallback to general implementation */
2518 break;
2519 }
2520
2521 /* general implementation */
2522 VISIT(c, expr, e);
2523 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2524 return 1;
2525}
2526
2527static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002528compiler_ifexp(struct compiler *c, expr_ty e)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 basicblock *end, *next;
2531
2532 assert(e->kind == IfExp_kind);
2533 end = compiler_new_block(c);
2534 if (end == NULL)
2535 return 0;
2536 next = compiler_new_block(c);
2537 if (next == NULL)
2538 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002539 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2540 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 VISIT(c, expr, e->v.IfExp.body);
2542 ADDOP_JREL(c, JUMP_FORWARD, end);
2543 compiler_use_next_block(c, next);
2544 VISIT(c, expr, e->v.IfExp.orelse);
2545 compiler_use_next_block(c, end);
2546 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002547}
2548
2549static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550compiler_lambda(struct compiler *c, expr_ty e)
2551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002553 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002555 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 arguments_ty args = e->v.Lambda.args;
2557 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (!name) {
2560 name = PyUnicode_InternFromString("<lambda>");
2561 if (!name)
2562 return 0;
2563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002565 funcflags = compiler_default_arguments(c, args);
2566 if (funcflags == -1) {
2567 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002569
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002570 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002571 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* Make None the first constant, so the lambda can't have a
2575 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002576 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002580 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2582 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2583 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002584 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 }
2586 else {
2587 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002588 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002590 qualname = c->u->u_qualname;
2591 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002593 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002596 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002597 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 Py_DECREF(co);
2599
2600 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601}
2602
2603static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604compiler_if(struct compiler *c, stmt_ty s)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 basicblock *end, *next;
2607 int constant;
2608 assert(s->kind == If_kind);
2609 end = compiler_new_block(c);
2610 if (end == NULL)
2611 return 0;
2612
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002613 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002614 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 * constant = 1: "if 1", "if 2", ...
2616 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002617 if (constant == 0) {
2618 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002620 END_DO_NOT_EMIT_BYTECODE
2621 if (s->v.If.orelse) {
2622 VISIT_SEQ(c, stmt, s->v.If.orelse);
2623 }
2624 } else if (constant == 1) {
2625 VISIT_SEQ(c, stmt, s->v.If.body);
2626 if (s->v.If.orelse) {
2627 BEGIN_DO_NOT_EMIT_BYTECODE
2628 VISIT_SEQ(c, stmt, s->v.If.orelse);
2629 END_DO_NOT_EMIT_BYTECODE
2630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002632 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 next = compiler_new_block(c);
2634 if (next == NULL)
2635 return 0;
2636 }
2637 else
2638 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002639 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2640 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002642 if (asdl_seq_LEN(s->v.If.orelse)) {
2643 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 compiler_use_next_block(c, next);
2645 VISIT_SEQ(c, stmt, s->v.If.orelse);
2646 }
2647 }
2648 compiler_use_next_block(c, end);
2649 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650}
2651
2652static int
2653compiler_for(struct compiler *c, stmt_ty s)
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 start = compiler_new_block(c);
2658 cleanup = compiler_new_block(c);
2659 end = compiler_new_block(c);
2660 if (start == NULL || end == NULL || cleanup == NULL)
2661 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002662
2663 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 VISIT(c, expr, s->v.For.iter);
2667 ADDOP(c, GET_ITER);
2668 compiler_use_next_block(c, start);
2669 ADDOP_JREL(c, FOR_ITER, cleanup);
2670 VISIT(c, expr, s->v.For.target);
2671 VISIT_SEQ(c, stmt, s->v.For.body);
2672 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2673 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002674
2675 compiler_pop_fblock(c, FOR_LOOP, start);
2676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 VISIT_SEQ(c, stmt, s->v.For.orelse);
2678 compiler_use_next_block(c, end);
2679 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680}
2681
Yury Selivanov75445082015-05-11 22:57:16 -04002682
2683static int
2684compiler_async_for(struct compiler *c, stmt_ty s)
2685{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002686 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002687 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2688 c->u->u_ste->ste_coroutine = 1;
2689 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002690 return compiler_error(c, "'async for' outside async function");
2691 }
2692
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002693 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002694 except = compiler_new_block(c);
2695 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002696
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002697 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002698 return 0;
2699
2700 VISIT(c, expr, s->v.AsyncFor.iter);
2701 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002702
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002703 compiler_use_next_block(c, start);
2704 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2705 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002707 /* SETUP_FINALLY to guard the __anext__ call */
2708 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002709 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002710 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002711 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002712 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002713
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002714 /* Success block for __anext__ */
2715 VISIT(c, expr, s->v.AsyncFor.target);
2716 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2717 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2718
2719 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002720
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002721 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002722 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002723 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002724
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002725 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002726 VISIT_SEQ(c, stmt, s->v.For.orelse);
2727
2728 compiler_use_next_block(c, end);
2729
2730 return 1;
2731}
2732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733static int
2734compiler_while(struct compiler *c, stmt_ty s)
2735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002737 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002740 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002741 // Push a dummy block so the VISIT_SEQ knows that we are
2742 // inside a while loop so it can correctly evaluate syntax
2743 // errors.
2744 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL)) {
2745 return 0;
2746 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002747 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002748 // Remove the dummy block now that is not needed.
2749 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002750 END_DO_NOT_EMIT_BYTECODE
2751 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002753 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 return 1;
2755 }
2756 loop = compiler_new_block(c);
2757 end = compiler_new_block(c);
2758 if (constant == -1) {
2759 anchor = compiler_new_block(c);
2760 if (anchor == NULL)
2761 return 0;
2762 }
2763 if (loop == NULL || end == NULL)
2764 return 0;
2765 if (s->v.While.orelse) {
2766 orelse = compiler_new_block(c);
2767 if (orelse == NULL)
2768 return 0;
2769 }
2770 else
2771 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 return 0;
2776 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002777 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2778 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 }
2780 VISIT_SEQ(c, stmt, s->v.While.body);
2781 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* XXX should the two POP instructions be in a separate block
2784 if there is no else clause ?
2785 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002787 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 compiler_pop_fblock(c, WHILE_LOOP, loop);
2790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (orelse != NULL) /* what if orelse is just pass? */
2792 VISIT_SEQ(c, stmt, s->v.While.orelse);
2793 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796}
2797
2798static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002799compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002802 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 if (c->u->u_ste->ste_type != FunctionBlock)
2804 return compiler_error(c, "'return' outside function");
2805 if (s->v.Return.value != NULL &&
2806 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2807 {
2808 return compiler_error(
2809 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 if (preserve_tos) {
2812 VISIT(c, expr, s->v.Return.value);
2813 }
2814 for (int depth = c->u->u_nfblocks; depth--;) {
2815 struct fblockinfo *info = &c->u->u_fblock[depth];
2816
2817 if (!compiler_unwind_fblock(c, info, preserve_tos))
2818 return 0;
2819 }
2820 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002821 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002822 }
2823 else if (!preserve_tos) {
2824 VISIT(c, expr, s->v.Return.value);
2825 }
2826 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829}
2830
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002831static int
2832compiler_break(struct compiler *c)
2833{
2834 for (int depth = c->u->u_nfblocks; depth--;) {
2835 struct fblockinfo *info = &c->u->u_fblock[depth];
2836
2837 if (!compiler_unwind_fblock(c, info, 0))
2838 return 0;
2839 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2840 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2841 return 1;
2842 }
2843 }
2844 return compiler_error(c, "'break' outside loop");
2845}
2846
2847static int
2848compiler_continue(struct compiler *c)
2849{
2850 for (int depth = c->u->u_nfblocks; depth--;) {
2851 struct fblockinfo *info = &c->u->u_fblock[depth];
2852
2853 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2854 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2855 return 1;
2856 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002857 if (!compiler_unwind_fblock(c, info, 0))
2858 return 0;
2859 }
2860 return compiler_error(c, "'continue' not properly in loop");
2861}
2862
2863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865
2866 SETUP_FINALLY L
2867 <code for body>
2868 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002869 BEGIN_FINALLY
2870 L:
2871 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 END_FINALLY
2873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 The special instructions use the block stack. Each block
2875 stack entry contains the instruction that created it (here
2876 SETUP_FINALLY), the level of the value stack at the time the
2877 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 Pushes the current value stack level and the label
2881 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 Pops en entry from the block stack.
2884 BEGIN_FINALLY
2885 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002887 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2888 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 when a SETUP_FINALLY entry is found, the raised and the caught
2892 exceptions are pushed onto the value stack (and the exception
2893 condition is cleared), and the interpreter jumps to the label
2894 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895*/
2896
2897static int
2898compiler_try_finally(struct compiler *c, stmt_ty s)
2899{
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002900 basicblock *start, *newcurblock, *body, *end;
2901 int break_finally = 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 body = compiler_new_block(c);
2904 end = compiler_new_block(c);
2905 if (body == NULL || end == NULL)
2906 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002908 start = c->u->u_curblock;
2909
2910 /* `finally` block. Compile it first to determine if any of "break",
2911 "continue" or "return" are used in it. */
2912 compiler_use_next_block(c, end);
2913 if (!compiler_push_fblock(c, FINALLY_END, end, end))
2914 return 0;
2915 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2916 ADDOP(c, END_FINALLY);
2917 break_finally = (c->u->u_fblock[c->u->u_nfblocks - 1].fb_exit == NULL);
2918 if (break_finally) {
2919 /* Pops a placeholder. See below */
2920 ADDOP(c, POP_TOP);
2921 }
2922 compiler_pop_fblock(c, FINALLY_END, end);
2923
2924 newcurblock = c->u->u_curblock;
2925 c->u->u_curblock = start;
2926 start->b_next = NULL;
2927
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002928 /* `try` block */
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002929 c->u->u_lineno_set = 0;
2930 c->u->u_lineno = s->lineno;
2931 c->u->u_col_offset = s->col_offset;
2932 if (break_finally) {
2933 /* Pushes a placeholder for the value of "return" in the "try" block
2934 to balance the stack for "break", "continue" and "return" in
2935 the "finally" block. */
2936 ADDOP_LOAD_CONST(c, Py_None);
2937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 ADDOP_JREL(c, SETUP_FINALLY, end);
2939 compiler_use_next_block(c, body);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002940 if (!compiler_push_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002942 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2943 if (!compiler_try_except(c, s))
2944 return 0;
2945 }
2946 else {
2947 VISIT_SEQ(c, stmt, s->v.Try.body);
2948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 ADDOP(c, BEGIN_FINALLY);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002951 compiler_pop_fblock(c, break_finally ? FINALLY_TRY2 : FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952
Serhiy Storchakaef61c522019-08-24 13:11:52 +03002953 c->u->u_curblock->b_next = end;
2954 c->u->u_curblock = newcurblock;
2955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957}
2958
2959/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002960 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 (The contents of the value stack is shown in [], with the top
2962 at the right; 'tb' is trace-back info, 'val' the exception's
2963 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964
2965 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002966 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 [] <code for S>
2968 [] POP_BLOCK
2969 [] JUMP_FORWARD L0
2970
2971 [tb, val, exc] L1: DUP )
2972 [tb, val, exc, exc] <evaluate E1> )
2973 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2974 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2975 [tb, val, exc] POP
2976 [tb, val] <assign to V1> (or POP if no V1)
2977 [tb] POP
2978 [] <code for S1>
2979 JUMP_FORWARD L0
2980
2981 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 .............................etc.......................
2983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2985
2986 [] L0: <next statement>
2987
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988 Of course, parts are not generated if Vi or Ei is not present.
2989*/
2990static int
2991compiler_try_except(struct compiler *c, stmt_ty s)
2992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002994 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 body = compiler_new_block(c);
2997 except = compiler_new_block(c);
2998 orelse = compiler_new_block(c);
2999 end = compiler_new_block(c);
3000 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3001 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003002 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003004 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003006 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 ADDOP(c, POP_BLOCK);
3008 compiler_pop_fblock(c, EXCEPT, body);
3009 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003010 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 compiler_use_next_block(c, except);
3012 for (i = 0; i < n; i++) {
3013 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003014 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 if (!handler->v.ExceptHandler.type && i < n-1)
3016 return compiler_error(c, "default 'except:' must be last");
3017 c->u->u_lineno_set = 0;
3018 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003019 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 except = compiler_new_block(c);
3021 if (except == NULL)
3022 return 0;
3023 if (handler->v.ExceptHandler.type) {
3024 ADDOP(c, DUP_TOP);
3025 VISIT(c, expr, handler->v.ExceptHandler.type);
3026 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3027 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3028 }
3029 ADDOP(c, POP_TOP);
3030 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003031 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003032
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003033 cleanup_end = compiler_new_block(c);
3034 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003035 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003036 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003037 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003038
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003039 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3040 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003042 /*
3043 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003044 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003045 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003046 try:
3047 # body
3048 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003049 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003050 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003051 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003053 /* second try: */
3054 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3055 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003056 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 /* second # body */
3060 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
3061 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003062 ADDOP(c, BEGIN_FINALLY);
3063 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003066 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003067 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003070 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003071 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02003076 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 }
3079 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003083 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085
Guido van Rossumb940e112007-01-10 16:19:56 +00003086 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 ADDOP(c, POP_TOP);
3088 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003089 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003090 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003092 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003093 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 }
3095 ADDOP_JREL(c, JUMP_FORWARD, end);
3096 compiler_use_next_block(c, except);
3097 }
3098 ADDOP(c, END_FINALLY);
3099 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003100 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 compiler_use_next_block(c, end);
3102 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103}
3104
3105static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003106compiler_try(struct compiler *c, stmt_ty s) {
3107 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3108 return compiler_try_finally(c, s);
3109 else
3110 return compiler_try_except(c, s);
3111}
3112
3113
3114static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115compiler_import_as(struct compiler *c, identifier name, identifier asname)
3116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 /* The IMPORT_NAME opcode was already generated. This function
3118 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003121 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003123 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3124 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003125 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003126 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003127 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003129 while (1) {
3130 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003132 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003134 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003135 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003137 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003138 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003139 if (dot == -1) {
3140 break;
3141 }
3142 ADDOP(c, ROT_TWO);
3143 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003145 if (!compiler_nameop(c, asname, Store)) {
3146 return 0;
3147 }
3148 ADDOP(c, POP_TOP);
3149 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 }
3151 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152}
3153
3154static int
3155compiler_import(struct compiler *c, stmt_ty s)
3156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* The Import node stores a module name like a.b.c as a single
3158 string. This is convenient for all cases except
3159 import a.b.c as d
3160 where we need to parse that string to extract the individual
3161 module names.
3162 XXX Perhaps change the representation to make this case simpler?
3163 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003164 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 for (i = 0; i < n; i++) {
3167 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3168 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003170 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3171 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 if (alias->asname) {
3175 r = compiler_import_as(c, alias->name, alias->asname);
3176 if (!r)
3177 return r;
3178 }
3179 else {
3180 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003181 Py_ssize_t dot = PyUnicode_FindChar(
3182 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003183 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003184 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003185 if (tmp == NULL)
3186 return 0;
3187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003189 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 Py_DECREF(tmp);
3191 }
3192 if (!r)
3193 return r;
3194 }
3195 }
3196 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197}
3198
3199static int
3200compiler_from_import(struct compiler *c, stmt_ty s)
3201{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003202 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003203 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 if (!empty_string) {
3207 empty_string = PyUnicode_FromString("");
3208 if (!empty_string)
3209 return 0;
3210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003212 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003213
3214 names = PyTuple_New(n);
3215 if (!names)
3216 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 /* build up the names */
3219 for (i = 0; i < n; i++) {
3220 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3221 Py_INCREF(alias->name);
3222 PyTuple_SET_ITEM(names, i, alias->name);
3223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003226 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 Py_DECREF(names);
3228 return compiler_error(c, "from __future__ imports must occur "
3229 "at the beginning of the file");
3230 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003231 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 if (s->v.ImportFrom.module) {
3234 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3235 }
3236 else {
3237 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3238 }
3239 for (i = 0; i < n; i++) {
3240 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3241 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003243 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 assert(n == 1);
3245 ADDOP(c, IMPORT_STAR);
3246 return 1;
3247 }
3248
3249 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3250 store_name = alias->name;
3251 if (alias->asname)
3252 store_name = alias->asname;
3253
3254 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 return 0;
3256 }
3257 }
3258 /* remove imported module */
3259 ADDOP(c, POP_TOP);
3260 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261}
3262
3263static int
3264compiler_assert(struct compiler *c, stmt_ty s)
3265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Georg Brandl8334fd92010-12-04 10:26:46 +00003268 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003271 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3272 {
3273 if (!compiler_warn(c, "assertion is always true, "
3274 "perhaps remove parentheses?"))
3275 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003276 return 0;
3277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 end = compiler_new_block(c);
3280 if (end == NULL)
3281 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003282 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3283 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003284 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 if (s->v.Assert.msg) {
3286 VISIT(c, expr, s->v.Assert.msg);
3287 ADDOP_I(c, CALL_FUNCTION, 1);
3288 }
3289 ADDOP_I(c, RAISE_VARARGS, 1);
3290 compiler_use_next_block(c, end);
3291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292}
3293
3294static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003295compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3296{
3297 if (c->c_interactive && c->c_nestlevel <= 1) {
3298 VISIT(c, expr, value);
3299 ADDOP(c, PRINT_EXPR);
3300 return 1;
3301 }
3302
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003303 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003304 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003305 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003306 }
3307
3308 VISIT(c, expr, value);
3309 ADDOP(c, POP_TOP);
3310 return 1;
3311}
3312
3313static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314compiler_visit_stmt(struct compiler *c, stmt_ty s)
3315{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003316 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 /* Always assign a lineno to the next instruction for a stmt. */
3319 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003320 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 switch (s->kind) {
3324 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003325 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 case ClassDef_kind:
3327 return compiler_class(c, s);
3328 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003329 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 case Delete_kind:
3331 VISIT_SEQ(c, expr, s->v.Delete.targets)
3332 break;
3333 case Assign_kind:
3334 n = asdl_seq_LEN(s->v.Assign.targets);
3335 VISIT(c, expr, s->v.Assign.value);
3336 for (i = 0; i < n; i++) {
3337 if (i < n - 1)
3338 ADDOP(c, DUP_TOP);
3339 VISIT(c, expr,
3340 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3341 }
3342 break;
3343 case AugAssign_kind:
3344 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003345 case AnnAssign_kind:
3346 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 case For_kind:
3348 return compiler_for(c, s);
3349 case While_kind:
3350 return compiler_while(c, s);
3351 case If_kind:
3352 return compiler_if(c, s);
3353 case Raise_kind:
3354 n = 0;
3355 if (s->v.Raise.exc) {
3356 VISIT(c, expr, s->v.Raise.exc);
3357 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003358 if (s->v.Raise.cause) {
3359 VISIT(c, expr, s->v.Raise.cause);
3360 n++;
3361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003363 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003365 case Try_kind:
3366 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 case Assert_kind:
3368 return compiler_assert(c, s);
3369 case Import_kind:
3370 return compiler_import(c, s);
3371 case ImportFrom_kind:
3372 return compiler_from_import(c, s);
3373 case Global_kind:
3374 case Nonlocal_kind:
3375 break;
3376 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003377 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 case Pass_kind:
3379 break;
3380 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003381 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 case Continue_kind:
3383 return compiler_continue(c);
3384 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003385 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003386 case AsyncFunctionDef_kind:
3387 return compiler_function(c, s, 1);
3388 case AsyncWith_kind:
3389 return compiler_async_with(c, s, 0);
3390 case AsyncFor_kind:
3391 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 }
Yury Selivanov75445082015-05-11 22:57:16 -04003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395}
3396
3397static int
3398unaryop(unaryop_ty op)
3399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 switch (op) {
3401 case Invert:
3402 return UNARY_INVERT;
3403 case Not:
3404 return UNARY_NOT;
3405 case UAdd:
3406 return UNARY_POSITIVE;
3407 case USub:
3408 return UNARY_NEGATIVE;
3409 default:
3410 PyErr_Format(PyExc_SystemError,
3411 "unary op %d should not be possible", op);
3412 return 0;
3413 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414}
3415
3416static int
3417binop(struct compiler *c, operator_ty op)
3418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 switch (op) {
3420 case Add:
3421 return BINARY_ADD;
3422 case Sub:
3423 return BINARY_SUBTRACT;
3424 case Mult:
3425 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003426 case MatMult:
3427 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 case Div:
3429 return BINARY_TRUE_DIVIDE;
3430 case Mod:
3431 return BINARY_MODULO;
3432 case Pow:
3433 return BINARY_POWER;
3434 case LShift:
3435 return BINARY_LSHIFT;
3436 case RShift:
3437 return BINARY_RSHIFT;
3438 case BitOr:
3439 return BINARY_OR;
3440 case BitXor:
3441 return BINARY_XOR;
3442 case BitAnd:
3443 return BINARY_AND;
3444 case FloorDiv:
3445 return BINARY_FLOOR_DIVIDE;
3446 default:
3447 PyErr_Format(PyExc_SystemError,
3448 "binary op %d should not be possible", op);
3449 return 0;
3450 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003451}
3452
3453static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454inplace_binop(struct compiler *c, operator_ty op)
3455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 switch (op) {
3457 case Add:
3458 return INPLACE_ADD;
3459 case Sub:
3460 return INPLACE_SUBTRACT;
3461 case Mult:
3462 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003463 case MatMult:
3464 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 case Div:
3466 return INPLACE_TRUE_DIVIDE;
3467 case Mod:
3468 return INPLACE_MODULO;
3469 case Pow:
3470 return INPLACE_POWER;
3471 case LShift:
3472 return INPLACE_LSHIFT;
3473 case RShift:
3474 return INPLACE_RSHIFT;
3475 case BitOr:
3476 return INPLACE_OR;
3477 case BitXor:
3478 return INPLACE_XOR;
3479 case BitAnd:
3480 return INPLACE_AND;
3481 case FloorDiv:
3482 return INPLACE_FLOOR_DIVIDE;
3483 default:
3484 PyErr_Format(PyExc_SystemError,
3485 "inplace binary op %d should not be possible", op);
3486 return 0;
3487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488}
3489
3490static int
3491compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3492{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003493 int op, scope;
3494 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 PyObject *dict = c->u->u_names;
3498 PyObject *mangled;
3499 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003501 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3502 !_PyUnicode_EqualToASCIIString(name, "True") &&
3503 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003504
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003505 mangled = _Py_Mangle(c->u->u_private, name);
3506 if (!mangled)
3507 return 0;
3508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 op = 0;
3510 optype = OP_NAME;
3511 scope = PyST_GetScope(c->u->u_ste, mangled);
3512 switch (scope) {
3513 case FREE:
3514 dict = c->u->u_freevars;
3515 optype = OP_DEREF;
3516 break;
3517 case CELL:
3518 dict = c->u->u_cellvars;
3519 optype = OP_DEREF;
3520 break;
3521 case LOCAL:
3522 if (c->u->u_ste->ste_type == FunctionBlock)
3523 optype = OP_FAST;
3524 break;
3525 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003526 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 optype = OP_GLOBAL;
3528 break;
3529 case GLOBAL_EXPLICIT:
3530 optype = OP_GLOBAL;
3531 break;
3532 default:
3533 /* scope can be 0 */
3534 break;
3535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003538 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 switch (optype) {
3541 case OP_DEREF:
3542 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003543 case Load:
3544 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3545 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003546 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003547 op = STORE_DEREF;
3548 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 case AugLoad:
3550 case AugStore:
3551 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003552 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 case Param:
3554 default:
3555 PyErr_SetString(PyExc_SystemError,
3556 "param invalid for deref variable");
3557 return 0;
3558 }
3559 break;
3560 case OP_FAST:
3561 switch (ctx) {
3562 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003563 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003564 op = STORE_FAST;
3565 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 case Del: op = DELETE_FAST; break;
3567 case AugLoad:
3568 case AugStore:
3569 break;
3570 case Param:
3571 default:
3572 PyErr_SetString(PyExc_SystemError,
3573 "param invalid for local variable");
3574 return 0;
3575 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003576 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 return 1;
3578 case OP_GLOBAL:
3579 switch (ctx) {
3580 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003581 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003582 op = STORE_GLOBAL;
3583 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 case Del: op = DELETE_GLOBAL; break;
3585 case AugLoad:
3586 case AugStore:
3587 break;
3588 case Param:
3589 default:
3590 PyErr_SetString(PyExc_SystemError,
3591 "param invalid for global variable");
3592 return 0;
3593 }
3594 break;
3595 case OP_NAME:
3596 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003597 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003598 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003599 op = STORE_NAME;
3600 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 case Del: op = DELETE_NAME; break;
3602 case AugLoad:
3603 case AugStore:
3604 break;
3605 case Param:
3606 default:
3607 PyErr_SetString(PyExc_SystemError,
3608 "param invalid for name variable");
3609 return 0;
3610 }
3611 break;
3612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 assert(op);
3615 arg = compiler_add_o(c, dict, mangled);
3616 Py_DECREF(mangled);
3617 if (arg < 0)
3618 return 0;
3619 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620}
3621
3622static int
3623compiler_boolop(struct compiler *c, expr_ty e)
3624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003626 int jumpi;
3627 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 assert(e->kind == BoolOp_kind);
3631 if (e->v.BoolOp.op == And)
3632 jumpi = JUMP_IF_FALSE_OR_POP;
3633 else
3634 jumpi = JUMP_IF_TRUE_OR_POP;
3635 end = compiler_new_block(c);
3636 if (end == NULL)
3637 return 0;
3638 s = e->v.BoolOp.values;
3639 n = asdl_seq_LEN(s) - 1;
3640 assert(n >= 0);
3641 for (i = 0; i < n; ++i) {
3642 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3643 ADDOP_JABS(c, jumpi, end);
3644 }
3645 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3646 compiler_use_next_block(c, end);
3647 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648}
3649
3650static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003651starunpack_helper(struct compiler *c, asdl_seq *elts,
3652 int single_op, int inner_op, int outer_op)
3653{
3654 Py_ssize_t n = asdl_seq_LEN(elts);
3655 Py_ssize_t i, nsubitems = 0, nseen = 0;
3656 for (i = 0; i < n; i++) {
3657 expr_ty elt = asdl_seq_GET(elts, i);
3658 if (elt->kind == Starred_kind) {
3659 if (nseen) {
3660 ADDOP_I(c, inner_op, nseen);
3661 nseen = 0;
3662 nsubitems++;
3663 }
3664 VISIT(c, expr, elt->v.Starred.value);
3665 nsubitems++;
3666 }
3667 else {
3668 VISIT(c, expr, elt);
3669 nseen++;
3670 }
3671 }
3672 if (nsubitems) {
3673 if (nseen) {
3674 ADDOP_I(c, inner_op, nseen);
3675 nsubitems++;
3676 }
3677 ADDOP_I(c, outer_op, nsubitems);
3678 }
3679 else
3680 ADDOP_I(c, single_op, nseen);
3681 return 1;
3682}
3683
3684static int
3685assignment_helper(struct compiler *c, asdl_seq *elts)
3686{
3687 Py_ssize_t n = asdl_seq_LEN(elts);
3688 Py_ssize_t i;
3689 int seen_star = 0;
3690 for (i = 0; i < n; i++) {
3691 expr_ty elt = asdl_seq_GET(elts, i);
3692 if (elt->kind == Starred_kind && !seen_star) {
3693 if ((i >= (1 << 8)) ||
3694 (n-i-1 >= (INT_MAX >> 8)))
3695 return compiler_error(c,
3696 "too many expressions in "
3697 "star-unpacking assignment");
3698 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3699 seen_star = 1;
3700 asdl_seq_SET(elts, i, elt->v.Starred.value);
3701 }
3702 else if (elt->kind == Starred_kind) {
3703 return compiler_error(c,
3704 "two starred expressions in assignment");
3705 }
3706 }
3707 if (!seen_star) {
3708 ADDOP_I(c, UNPACK_SEQUENCE, n);
3709 }
3710 VISIT_SEQ(c, expr, elts);
3711 return 1;
3712}
3713
3714static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003715compiler_list(struct compiler *c, expr_ty e)
3716{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003718 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003719 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721 else if (e->v.List.ctx == Load) {
3722 return starunpack_helper(c, elts,
3723 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 else
3726 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728}
3729
3730static int
3731compiler_tuple(struct compiler *c, expr_ty e)
3732{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003734 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 return assignment_helper(c, elts);
3736 }
3737 else if (e->v.Tuple.ctx == Load) {
3738 return starunpack_helper(c, elts,
3739 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3740 }
3741 else
3742 VISIT_SEQ(c, expr, elts);
3743 return 1;
3744}
3745
3746static int
3747compiler_set(struct compiler *c, expr_ty e)
3748{
3749 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3750 BUILD_SET, BUILD_SET_UNPACK);
3751}
3752
3753static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003754are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3755{
3756 Py_ssize_t i;
3757 for (i = begin; i < end; i++) {
3758 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003759 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003760 return 0;
3761 }
3762 return 1;
3763}
3764
3765static int
3766compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3767{
3768 Py_ssize_t i, n = end - begin;
3769 PyObject *keys, *key;
3770 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3771 for (i = begin; i < end; i++) {
3772 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3773 }
3774 keys = PyTuple_New(n);
3775 if (keys == NULL) {
3776 return 0;
3777 }
3778 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003779 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003780 Py_INCREF(key);
3781 PyTuple_SET_ITEM(keys, i - begin, key);
3782 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003783 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003784 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3785 }
3786 else {
3787 for (i = begin; i < end; i++) {
3788 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3789 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3790 }
3791 ADDOP_I(c, BUILD_MAP, n);
3792 }
3793 return 1;
3794}
3795
3796static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797compiler_dict(struct compiler *c, expr_ty e)
3798{
Victor Stinner976bb402016-03-23 11:36:19 +01003799 Py_ssize_t i, n, elements;
3800 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003801 int is_unpacking = 0;
3802 n = asdl_seq_LEN(e->v.Dict.values);
3803 containers = 0;
3804 elements = 0;
3805 for (i = 0; i < n; i++) {
3806 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3807 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003808 if (!compiler_subdict(c, e, i - elements, i))
3809 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 containers++;
3811 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003813 if (is_unpacking) {
3814 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3815 containers++;
3816 }
3817 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 }
3820 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003822 if (!compiler_subdict(c, e, n - elements, n))
3823 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003824 containers++;
3825 }
3826 /* If there is more than one dict, they need to be merged into a new
3827 * dict. If there is one dict and it's an unpacking, then it needs
3828 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003829 if (containers > 1 || is_unpacking) {
3830 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
3832 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833}
3834
3835static int
3836compiler_compare(struct compiler *c, expr_ty e)
3837{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003838 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003839
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003840 if (!check_compare(c, e)) {
3841 return 0;
3842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003844 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3845 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3846 if (n == 0) {
3847 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3848 ADDOP_I(c, COMPARE_OP,
3849 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3850 }
3851 else {
3852 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 if (cleanup == NULL)
3854 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003855 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 VISIT(c, expr,
3857 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003858 ADDOP(c, DUP_TOP);
3859 ADDOP(c, ROT_THREE);
3860 ADDOP_I(c, COMPARE_OP,
3861 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3862 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3863 NEXT_BLOCK(c);
3864 }
3865 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3866 ADDOP_I(c, COMPARE_OP,
3867 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 basicblock *end = compiler_new_block(c);
3869 if (end == NULL)
3870 return 0;
3871 ADDOP_JREL(c, JUMP_FORWARD, end);
3872 compiler_use_next_block(c, cleanup);
3873 ADDOP(c, ROT_TWO);
3874 ADDOP(c, POP_TOP);
3875 compiler_use_next_block(c, end);
3876 }
3877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878}
3879
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003880static PyTypeObject *
3881infer_type(expr_ty e)
3882{
3883 switch (e->kind) {
3884 case Tuple_kind:
3885 return &PyTuple_Type;
3886 case List_kind:
3887 case ListComp_kind:
3888 return &PyList_Type;
3889 case Dict_kind:
3890 case DictComp_kind:
3891 return &PyDict_Type;
3892 case Set_kind:
3893 case SetComp_kind:
3894 return &PySet_Type;
3895 case GeneratorExp_kind:
3896 return &PyGen_Type;
3897 case Lambda_kind:
3898 return &PyFunction_Type;
3899 case JoinedStr_kind:
3900 case FormattedValue_kind:
3901 return &PyUnicode_Type;
3902 case Constant_kind:
3903 return e->v.Constant.value->ob_type;
3904 default:
3905 return NULL;
3906 }
3907}
3908
3909static int
3910check_caller(struct compiler *c, expr_ty e)
3911{
3912 switch (e->kind) {
3913 case Constant_kind:
3914 case Tuple_kind:
3915 case List_kind:
3916 case ListComp_kind:
3917 case Dict_kind:
3918 case DictComp_kind:
3919 case Set_kind:
3920 case SetComp_kind:
3921 case GeneratorExp_kind:
3922 case JoinedStr_kind:
3923 case FormattedValue_kind:
3924 return compiler_warn(c, "'%.200s' object is not callable; "
3925 "perhaps you missed a comma?",
3926 infer_type(e)->tp_name);
3927 default:
3928 return 1;
3929 }
3930}
3931
3932static int
3933check_subscripter(struct compiler *c, expr_ty e)
3934{
3935 PyObject *v;
3936
3937 switch (e->kind) {
3938 case Constant_kind:
3939 v = e->v.Constant.value;
3940 if (!(v == Py_None || v == Py_Ellipsis ||
3941 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3942 PyAnySet_Check(v)))
3943 {
3944 return 1;
3945 }
3946 /* fall through */
3947 case Set_kind:
3948 case SetComp_kind:
3949 case GeneratorExp_kind:
3950 case Lambda_kind:
3951 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3952 "perhaps you missed a comma?",
3953 infer_type(e)->tp_name);
3954 default:
3955 return 1;
3956 }
3957}
3958
3959static int
3960check_index(struct compiler *c, expr_ty e, slice_ty s)
3961{
3962 PyObject *v;
3963
3964 if (s->kind != Index_kind) {
3965 return 1;
3966 }
3967 PyTypeObject *index_type = infer_type(s->v.Index.value);
3968 if (index_type == NULL
3969 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3970 || index_type == &PySlice_Type) {
3971 return 1;
3972 }
3973
3974 switch (e->kind) {
3975 case Constant_kind:
3976 v = e->v.Constant.value;
3977 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3978 return 1;
3979 }
3980 /* fall through */
3981 case Tuple_kind:
3982 case List_kind:
3983 case ListComp_kind:
3984 case JoinedStr_kind:
3985 case FormattedValue_kind:
3986 return compiler_warn(c, "%.200s indices must be integers or slices, "
3987 "not %.200s; "
3988 "perhaps you missed a comma?",
3989 infer_type(e)->tp_name,
3990 index_type->tp_name);
3991 default:
3992 return 1;
3993 }
3994}
3995
Zackery Spytz97f5de02019-03-22 01:30:32 -06003996// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003997static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003998maybe_optimize_method_call(struct compiler *c, expr_ty e)
3999{
4000 Py_ssize_t argsl, i;
4001 expr_ty meth = e->v.Call.func;
4002 asdl_seq *args = e->v.Call.args;
4003
4004 /* Check that the call node is an attribute access, and that
4005 the call doesn't have keyword parameters. */
4006 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4007 asdl_seq_LEN(e->v.Call.keywords))
4008 return -1;
4009
4010 /* Check that there are no *varargs types of arguments. */
4011 argsl = asdl_seq_LEN(args);
4012 for (i = 0; i < argsl; i++) {
4013 expr_ty elt = asdl_seq_GET(args, i);
4014 if (elt->kind == Starred_kind) {
4015 return -1;
4016 }
4017 }
4018
4019 /* Alright, we can optimize the code. */
4020 VISIT(c, expr, meth->v.Attribute.value);
4021 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4022 VISIT_SEQ(c, expr, e->v.Call.args);
4023 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4024 return 1;
4025}
4026
4027static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028compiler_call(struct compiler *c, expr_ty e)
4029{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004030 int ret = maybe_optimize_method_call(c, e);
4031 if (ret >= 0) {
4032 return ret;
4033 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004034 if (!check_caller(c, e->v.Call.func)) {
4035 return 0;
4036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 VISIT(c, expr, e->v.Call.func);
4038 return compiler_call_helper(c, 0,
4039 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004040 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004041}
4042
Eric V. Smith235a6f02015-09-19 14:51:32 -04004043static int
4044compiler_joined_str(struct compiler *c, expr_ty e)
4045{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004046 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004047 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4048 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004049 return 1;
4050}
4051
Eric V. Smitha78c7952015-11-03 12:45:05 -05004052/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004053static int
4054compiler_formatted_value(struct compiler *c, expr_ty e)
4055{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004056 /* Our oparg encodes 2 pieces of information: the conversion
4057 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004058
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004059 Convert the conversion char to 3 bits:
4060 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004061 !s : 001 0x1 FVC_STR
4062 !r : 010 0x2 FVC_REPR
4063 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004064
Eric V. Smitha78c7952015-11-03 12:45:05 -05004065 next bit is whether or not we have a format spec:
4066 yes : 100 0x4
4067 no : 000 0x0
4068 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004069
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004070 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004071 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004072
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004073 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004074 VISIT(c, expr, e->v.FormattedValue.value);
4075
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004076 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004077 case 's': oparg = FVC_STR; break;
4078 case 'r': oparg = FVC_REPR; break;
4079 case 'a': oparg = FVC_ASCII; break;
4080 case -1: oparg = FVC_NONE; break;
4081 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004082 PyErr_Format(PyExc_SystemError,
4083 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004084 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004085 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004086 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004087 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004088 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004089 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004090 }
4091
Eric V. Smitha78c7952015-11-03 12:45:05 -05004092 /* And push our opcode and oparg */
4093 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004094
Eric V. Smith235a6f02015-09-19 14:51:32 -04004095 return 1;
4096}
4097
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004098static int
4099compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4100{
4101 Py_ssize_t i, n = end - begin;
4102 keyword_ty kw;
4103 PyObject *keys, *key;
4104 assert(n > 0);
4105 if (n > 1) {
4106 for (i = begin; i < end; i++) {
4107 kw = asdl_seq_GET(keywords, i);
4108 VISIT(c, expr, kw->value);
4109 }
4110 keys = PyTuple_New(n);
4111 if (keys == NULL) {
4112 return 0;
4113 }
4114 for (i = begin; i < end; i++) {
4115 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4116 Py_INCREF(key);
4117 PyTuple_SET_ITEM(keys, i - begin, key);
4118 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004119 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004120 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4121 }
4122 else {
4123 /* a for loop only executes once */
4124 for (i = begin; i < end; i++) {
4125 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004126 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004127 VISIT(c, expr, kw->value);
4128 }
4129 ADDOP_I(c, BUILD_MAP, n);
4130 }
4131 return 1;
4132}
4133
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004134/* shared code between compiler_call and compiler_class */
4135static int
4136compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004137 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004138 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004139 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004140{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004141 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004142 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004143
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004144 /* the number of tuples and dictionaries on the stack */
4145 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4146
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004147 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004148 nkwelts = asdl_seq_LEN(keywords);
4149
4150 for (i = 0; i < nkwelts; i++) {
4151 keyword_ty kw = asdl_seq_GET(keywords, i);
4152 if (kw->arg == NULL) {
4153 mustdictunpack = 1;
4154 break;
4155 }
4156 }
4157
4158 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004159 for (i = 0; i < nelts; i++) {
4160 expr_ty elt = asdl_seq_GET(args, i);
4161 if (elt->kind == Starred_kind) {
4162 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004163 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004164 if (nseen) {
4165 ADDOP_I(c, BUILD_TUPLE, nseen);
4166 nseen = 0;
4167 nsubargs++;
4168 }
4169 VISIT(c, expr, elt->v.Starred.value);
4170 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004171 }
4172 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004173 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004174 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004177
4178 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004179 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004180 if (nseen) {
4181 /* Pack up any trailing positional arguments. */
4182 ADDOP_I(c, BUILD_TUPLE, nseen);
4183 nsubargs++;
4184 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004185 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004186 /* If we ended up with more than one stararg, we need
4187 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004188 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004189 }
4190 else if (nsubargs == 0) {
4191 ADDOP_I(c, BUILD_TUPLE, 0);
4192 }
4193 nseen = 0; /* the number of keyword arguments on the stack following */
4194 for (i = 0; i < nkwelts; i++) {
4195 keyword_ty kw = asdl_seq_GET(keywords, i);
4196 if (kw->arg == NULL) {
4197 /* A keyword argument unpacking. */
4198 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004199 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4200 return 0;
4201 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004202 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004203 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004204 VISIT(c, expr, kw->value);
4205 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004206 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004207 else {
4208 nseen++;
4209 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004210 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004211 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004212 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004213 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004214 return 0;
4215 nsubkwargs++;
4216 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004217 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004218 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004219 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004220 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004221 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4222 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004224 else if (nkwelts) {
4225 PyObject *names;
4226 VISIT_SEQ(c, keyword, keywords);
4227 names = PyTuple_New(nkwelts);
4228 if (names == NULL) {
4229 return 0;
4230 }
4231 for (i = 0; i < nkwelts; i++) {
4232 keyword_ty kw = asdl_seq_GET(keywords, i);
4233 Py_INCREF(kw->arg);
4234 PyTuple_SET_ITEM(names, i, kw->arg);
4235 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004236 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004237 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4238 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004240 else {
4241 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4242 return 1;
4243 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004244}
4245
Nick Coghlan650f0d02007-04-15 12:05:43 +00004246
4247/* List and set comprehensions and generator expressions work by creating a
4248 nested function to perform the actual iteration. This means that the
4249 iteration variables don't leak into the current scope.
4250 The defined function is called immediately following its definition, with the
4251 result of that call being the result of the expression.
4252 The LC/SC version returns the populated container, while the GE version is
4253 flagged in symtable.c as a generator, so it returns the generator object
4254 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004255
4256 Possible cleanups:
4257 - iterate over the generator sequence instead of using recursion
4258*/
4259
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262compiler_comprehension_generator(struct compiler *c,
4263 asdl_seq *generators, int gen_index,
4264 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004265{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004266 comprehension_ty gen;
4267 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4268 if (gen->is_async) {
4269 return compiler_async_comprehension_generator(
4270 c, generators, gen_index, elt, val, type);
4271 } else {
4272 return compiler_sync_comprehension_generator(
4273 c, generators, gen_index, elt, val, type);
4274 }
4275}
4276
4277static int
4278compiler_sync_comprehension_generator(struct compiler *c,
4279 asdl_seq *generators, int gen_index,
4280 expr_ty elt, expr_ty val, int type)
4281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 /* generate code for the iterator, then each of the ifs,
4283 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 comprehension_ty gen;
4286 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004287 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 start = compiler_new_block(c);
4290 skip = compiler_new_block(c);
4291 if_cleanup = compiler_new_block(c);
4292 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4295 anchor == NULL)
4296 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 if (gen_index == 0) {
4301 /* Receive outermost iter as an implicit argument */
4302 c->u->u_argcount = 1;
4303 ADDOP_I(c, LOAD_FAST, 0);
4304 }
4305 else {
4306 /* Sub-iter - calculate on the fly */
4307 VISIT(c, expr, gen->iter);
4308 ADDOP(c, GET_ITER);
4309 }
4310 compiler_use_next_block(c, start);
4311 ADDOP_JREL(c, FOR_ITER, anchor);
4312 NEXT_BLOCK(c);
4313 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 /* XXX this needs to be cleaned up...a lot! */
4316 n = asdl_seq_LEN(gen->ifs);
4317 for (i = 0; i < n; i++) {
4318 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004319 if (!compiler_jump_if(c, e, if_cleanup, 0))
4320 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 NEXT_BLOCK(c);
4322 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 if (++gen_index < asdl_seq_LEN(generators))
4325 if (!compiler_comprehension_generator(c,
4326 generators, gen_index,
4327 elt, val, type))
4328 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 /* only append after the last for generator */
4331 if (gen_index >= asdl_seq_LEN(generators)) {
4332 /* comprehension specific code */
4333 switch (type) {
4334 case COMP_GENEXP:
4335 VISIT(c, expr, elt);
4336 ADDOP(c, YIELD_VALUE);
4337 ADDOP(c, POP_TOP);
4338 break;
4339 case COMP_LISTCOMP:
4340 VISIT(c, expr, elt);
4341 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4342 break;
4343 case COMP_SETCOMP:
4344 VISIT(c, expr, elt);
4345 ADDOP_I(c, SET_ADD, gen_index + 1);
4346 break;
4347 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004348 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004351 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 ADDOP_I(c, MAP_ADD, gen_index + 1);
4353 break;
4354 default:
4355 return 0;
4356 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 compiler_use_next_block(c, skip);
4359 }
4360 compiler_use_next_block(c, if_cleanup);
4361 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4362 compiler_use_next_block(c, anchor);
4363
4364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365}
4366
4367static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368compiler_async_comprehension_generator(struct compiler *c,
4369 asdl_seq *generators, int gen_index,
4370 expr_ty elt, expr_ty val, int type)
4371{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004373 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004374 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004375 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004377 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004378
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004379 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004380 return 0;
4381 }
4382
4383 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4384
4385 if (gen_index == 0) {
4386 /* Receive outermost iter as an implicit argument */
4387 c->u->u_argcount = 1;
4388 ADDOP_I(c, LOAD_FAST, 0);
4389 }
4390 else {
4391 /* Sub-iter - calculate on the fly */
4392 VISIT(c, expr, gen->iter);
4393 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004394 }
4395
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004396 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004397
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004398 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004399 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004400 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004401 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004402 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004403 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404
4405 n = asdl_seq_LEN(gen->ifs);
4406 for (i = 0; i < n; i++) {
4407 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004408 if (!compiler_jump_if(c, e, if_cleanup, 0))
4409 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004410 NEXT_BLOCK(c);
4411 }
4412
4413 if (++gen_index < asdl_seq_LEN(generators))
4414 if (!compiler_comprehension_generator(c,
4415 generators, gen_index,
4416 elt, val, type))
4417 return 0;
4418
4419 /* only append after the last for generator */
4420 if (gen_index >= asdl_seq_LEN(generators)) {
4421 /* comprehension specific code */
4422 switch (type) {
4423 case COMP_GENEXP:
4424 VISIT(c, expr, elt);
4425 ADDOP(c, YIELD_VALUE);
4426 ADDOP(c, POP_TOP);
4427 break;
4428 case COMP_LISTCOMP:
4429 VISIT(c, expr, elt);
4430 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4431 break;
4432 case COMP_SETCOMP:
4433 VISIT(c, expr, elt);
4434 ADDOP_I(c, SET_ADD, gen_index + 1);
4435 break;
4436 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004437 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004438 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004439 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004440 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004441 ADDOP_I(c, MAP_ADD, gen_index + 1);
4442 break;
4443 default:
4444 return 0;
4445 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004446 }
4447 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004448 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4449
4450 compiler_use_next_block(c, except);
4451 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004452
4453 return 1;
4454}
4455
4456static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004457compiler_comprehension(struct compiler *c, expr_ty e, int type,
4458 identifier name, asdl_seq *generators, expr_ty elt,
4459 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004463 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004464 int is_async_function = c->u->u_ste->ste_coroutine;
4465 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004466
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004467 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004468
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004469 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4470 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004471 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004473 }
4474
4475 is_async_generator = c->u->u_ste->ste_coroutine;
4476
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004477 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004478 compiler_error(c, "asynchronous comprehension outside of "
4479 "an asynchronous function");
4480 goto error_in_scope;
4481 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 if (type != COMP_GENEXP) {
4484 int op;
4485 switch (type) {
4486 case COMP_LISTCOMP:
4487 op = BUILD_LIST;
4488 break;
4489 case COMP_SETCOMP:
4490 op = BUILD_SET;
4491 break;
4492 case COMP_DICTCOMP:
4493 op = BUILD_MAP;
4494 break;
4495 default:
4496 PyErr_Format(PyExc_SystemError,
4497 "unknown comprehension type %d", type);
4498 goto error_in_scope;
4499 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 ADDOP_I(c, op, 0);
4502 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (!compiler_comprehension_generator(c, generators, 0, elt,
4505 val, type))
4506 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (type != COMP_GENEXP) {
4509 ADDOP(c, RETURN_VALUE);
4510 }
4511
4512 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004513 qualname = c->u->u_qualname;
4514 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004516 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 goto error;
4518
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004519 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004521 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 Py_DECREF(co);
4523
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 VISIT(c, expr, outermost->iter);
4525
4526 if (outermost->is_async) {
4527 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 } else {
4529 ADDOP(c, GET_ITER);
4530 }
4531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533
4534 if (is_async_generator && type != COMP_GENEXP) {
4535 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004536 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 ADDOP(c, YIELD_FROM);
4538 }
4539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004541error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004543error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004544 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 Py_XDECREF(co);
4546 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004547}
4548
4549static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004550compiler_genexp(struct compiler *c, expr_ty e)
4551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 static identifier name;
4553 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004554 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 if (!name)
4556 return 0;
4557 }
4558 assert(e->kind == GeneratorExp_kind);
4559 return compiler_comprehension(c, e, COMP_GENEXP, name,
4560 e->v.GeneratorExp.generators,
4561 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004562}
4563
4564static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004565compiler_listcomp(struct compiler *c, expr_ty e)
4566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 static identifier name;
4568 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004569 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (!name)
4571 return 0;
4572 }
4573 assert(e->kind == ListComp_kind);
4574 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4575 e->v.ListComp.generators,
4576 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004577}
4578
4579static int
4580compiler_setcomp(struct compiler *c, expr_ty e)
4581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 static identifier name;
4583 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004584 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 if (!name)
4586 return 0;
4587 }
4588 assert(e->kind == SetComp_kind);
4589 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4590 e->v.SetComp.generators,
4591 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004592}
4593
4594
4595static int
4596compiler_dictcomp(struct compiler *c, expr_ty e)
4597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 static identifier name;
4599 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004600 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 if (!name)
4602 return 0;
4603 }
4604 assert(e->kind == DictComp_kind);
4605 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4606 e->v.DictComp.generators,
4607 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004608}
4609
4610
4611static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004612compiler_visit_keyword(struct compiler *c, keyword_ty k)
4613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 VISIT(c, expr, k->value);
4615 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004616}
4617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004619 whether they are true or false.
4620
4621 Return values: 1 for true, 0 for false, -1 for non-constant.
4622 */
4623
4624static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004625expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004626{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004627 if (e->kind == Constant_kind) {
4628 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004629 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004630 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004631}
4632
Yury Selivanov75445082015-05-11 22:57:16 -04004633
4634/*
4635 Implements the async with statement.
4636
4637 The semantics outlined in that PEP are as follows:
4638
4639 async with EXPR as VAR:
4640 BLOCK
4641
4642 It is implemented roughly as:
4643
4644 context = EXPR
4645 exit = context.__aexit__ # not calling it
4646 value = await context.__aenter__()
4647 try:
4648 VAR = value # if VAR present in the syntax
4649 BLOCK
4650 finally:
4651 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004652 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004653 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004654 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004655 if not (await exit(*exc)):
4656 raise
4657 */
4658static int
4659compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4660{
4661 basicblock *block, *finally;
4662 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4663
4664 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004665 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4666 c->u->u_ste->ste_coroutine = 1;
4667 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004668 return compiler_error(c, "'async with' outside async function");
4669 }
Yury Selivanov75445082015-05-11 22:57:16 -04004670
4671 block = compiler_new_block(c);
4672 finally = compiler_new_block(c);
4673 if (!block || !finally)
4674 return 0;
4675
4676 /* Evaluate EXPR */
4677 VISIT(c, expr, item->context_expr);
4678
4679 ADDOP(c, BEFORE_ASYNC_WITH);
4680 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004681 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004682 ADDOP(c, YIELD_FROM);
4683
4684 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4685
4686 /* SETUP_ASYNC_WITH pushes a finally block. */
4687 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004688 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004689 return 0;
4690 }
4691
4692 if (item->optional_vars) {
4693 VISIT(c, expr, item->optional_vars);
4694 }
4695 else {
4696 /* Discard result from context.__aenter__() */
4697 ADDOP(c, POP_TOP);
4698 }
4699
4700 pos++;
4701 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4702 /* BLOCK code */
4703 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4704 else if (!compiler_async_with(c, s, pos))
4705 return 0;
4706
4707 /* End of try block; start the finally block */
4708 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004709 ADDOP(c, BEGIN_FINALLY);
4710 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004711
Yury Selivanov75445082015-05-11 22:57:16 -04004712 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004713 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004714 return 0;
4715
4716 /* Finally block starts; context.__exit__ is on the stack under
4717 the exception or return information. Just issue our magic
4718 opcode. */
4719 ADDOP(c, WITH_CLEANUP_START);
4720
4721 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004722 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004723 ADDOP(c, YIELD_FROM);
4724
4725 ADDOP(c, WITH_CLEANUP_FINISH);
4726
4727 /* Finally block ends. */
4728 ADDOP(c, END_FINALLY);
4729 compiler_pop_fblock(c, FINALLY_END, finally);
4730 return 1;
4731}
4732
4733
Guido van Rossumc2e20742006-02-27 22:32:47 +00004734/*
4735 Implements the with statement from PEP 343.
4736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004738
4739 with EXPR as VAR:
4740 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741
Guido van Rossumc2e20742006-02-27 22:32:47 +00004742 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743
Thomas Wouters477c8d52006-05-27 19:21:47 +00004744 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004745 exit = context.__exit__ # not calling it
4746 value = context.__enter__()
4747 try:
4748 VAR = value # if VAR present in the syntax
4749 BLOCK
4750 finally:
4751 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004752 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004753 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004754 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004755 exit(*exc)
4756 */
4757static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004758compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004759{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004760 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004761 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004762
4763 assert(s->kind == With_kind);
4764
Guido van Rossumc2e20742006-02-27 22:32:47 +00004765 block = compiler_new_block(c);
4766 finally = compiler_new_block(c);
4767 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004768 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004769
Thomas Wouters477c8d52006-05-27 19:21:47 +00004770 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004771 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004772 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004773
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004774 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004775 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004776 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004777 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004778 }
4779
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004780 if (item->optional_vars) {
4781 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004782 }
4783 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004785 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004786 }
4787
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004788 pos++;
4789 if (pos == asdl_seq_LEN(s->v.With.items))
4790 /* BLOCK code */
4791 VISIT_SEQ(c, stmt, s->v.With.body)
4792 else if (!compiler_with(c, s, pos))
4793 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004794
4795 /* End of try block; start the finally block */
4796 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004797 ADDOP(c, BEGIN_FINALLY);
4798 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004799
Guido van Rossumc2e20742006-02-27 22:32:47 +00004800 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004801 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004802 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004803
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004804 /* Finally block starts; context.__exit__ is on the stack under
4805 the exception or return information. Just issue our magic
4806 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004807 ADDOP(c, WITH_CLEANUP_START);
4808 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004809
4810 /* Finally block ends. */
4811 ADDOP(c, END_FINALLY);
4812 compiler_pop_fblock(c, FINALLY_END, finally);
4813 return 1;
4814}
4815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004816static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004817compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004820 case NamedExpr_kind:
4821 VISIT(c, expr, e->v.NamedExpr.value);
4822 ADDOP(c, DUP_TOP);
4823 VISIT(c, expr, e->v.NamedExpr.target);
4824 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 case BoolOp_kind:
4826 return compiler_boolop(c, e);
4827 case BinOp_kind:
4828 VISIT(c, expr, e->v.BinOp.left);
4829 VISIT(c, expr, e->v.BinOp.right);
4830 ADDOP(c, binop(c, e->v.BinOp.op));
4831 break;
4832 case UnaryOp_kind:
4833 VISIT(c, expr, e->v.UnaryOp.operand);
4834 ADDOP(c, unaryop(e->v.UnaryOp.op));
4835 break;
4836 case Lambda_kind:
4837 return compiler_lambda(c, e);
4838 case IfExp_kind:
4839 return compiler_ifexp(c, e);
4840 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004841 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004843 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 case GeneratorExp_kind:
4845 return compiler_genexp(c, e);
4846 case ListComp_kind:
4847 return compiler_listcomp(c, e);
4848 case SetComp_kind:
4849 return compiler_setcomp(c, e);
4850 case DictComp_kind:
4851 return compiler_dictcomp(c, e);
4852 case Yield_kind:
4853 if (c->u->u_ste->ste_type != FunctionBlock)
4854 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004855 if (e->v.Yield.value) {
4856 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 }
4858 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004859 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004861 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004863 case YieldFrom_kind:
4864 if (c->u->u_ste->ste_type != FunctionBlock)
4865 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004866
4867 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4868 return compiler_error(c, "'yield from' inside async function");
4869
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004870 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004871 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004872 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004873 ADDOP(c, YIELD_FROM);
4874 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004875 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004876 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4877 if (c->u->u_ste->ste_type != FunctionBlock){
4878 return compiler_error(c, "'await' outside function");
4879 }
Yury Selivanov75445082015-05-11 22:57:16 -04004880
Victor Stinner331a6a52019-05-27 16:39:22 +02004881 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004882 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4883 return compiler_error(c, "'await' outside async function");
4884 }
4885 }
Yury Selivanov75445082015-05-11 22:57:16 -04004886
4887 VISIT(c, expr, e->v.Await.value);
4888 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004889 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004890 ADDOP(c, YIELD_FROM);
4891 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 case Compare_kind:
4893 return compiler_compare(c, e);
4894 case Call_kind:
4895 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004896 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004897 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004898 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004899 case JoinedStr_kind:
4900 return compiler_joined_str(c, e);
4901 case FormattedValue_kind:
4902 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 /* The following exprs can be assignment targets. */
4904 case Attribute_kind:
4905 if (e->v.Attribute.ctx != AugStore)
4906 VISIT(c, expr, e->v.Attribute.value);
4907 switch (e->v.Attribute.ctx) {
4908 case AugLoad:
4909 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004910 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 case Load:
4912 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4913 break;
4914 case AugStore:
4915 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004916 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 case Store:
4918 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4919 break;
4920 case Del:
4921 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4922 break;
4923 case Param:
4924 default:
4925 PyErr_SetString(PyExc_SystemError,
4926 "param invalid in attribute expression");
4927 return 0;
4928 }
4929 break;
4930 case Subscript_kind:
4931 switch (e->v.Subscript.ctx) {
4932 case AugLoad:
4933 VISIT(c, expr, e->v.Subscript.value);
4934 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4935 break;
4936 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004937 if (!check_subscripter(c, e->v.Subscript.value)) {
4938 return 0;
4939 }
4940 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4941 return 0;
4942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 VISIT(c, expr, e->v.Subscript.value);
4944 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4945 break;
4946 case AugStore:
4947 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4948 break;
4949 case Store:
4950 VISIT(c, expr, e->v.Subscript.value);
4951 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4952 break;
4953 case Del:
4954 VISIT(c, expr, e->v.Subscript.value);
4955 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4956 break;
4957 case Param:
4958 default:
4959 PyErr_SetString(PyExc_SystemError,
4960 "param invalid in subscript expression");
4961 return 0;
4962 }
4963 break;
4964 case Starred_kind:
4965 switch (e->v.Starred.ctx) {
4966 case Store:
4967 /* In all legitimate cases, the Starred node was already replaced
4968 * by compiler_list/compiler_tuple. XXX: is that okay? */
4969 return compiler_error(c,
4970 "starred assignment target must be in a list or tuple");
4971 default:
4972 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004973 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 case Name_kind:
4976 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4977 /* child nodes of List and Tuple will have expr_context set */
4978 case List_kind:
4979 return compiler_list(c, e);
4980 case Tuple_kind:
4981 return compiler_tuple(c, e);
4982 }
4983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004984}
4985
4986static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004987compiler_visit_expr(struct compiler *c, expr_ty e)
4988{
4989 /* If expr e has a different line number than the last expr/stmt,
4990 set a new line number for the next instruction.
4991 */
4992 int old_lineno = c->u->u_lineno;
4993 int old_col_offset = c->u->u_col_offset;
4994 if (e->lineno != c->u->u_lineno) {
4995 c->u->u_lineno = e->lineno;
4996 c->u->u_lineno_set = 0;
4997 }
4998 /* Updating the column offset is always harmless. */
4999 c->u->u_col_offset = e->col_offset;
5000
5001 int res = compiler_visit_expr1(c, e);
5002
5003 if (old_lineno != c->u->u_lineno) {
5004 c->u->u_lineno = old_lineno;
5005 c->u->u_lineno_set = 0;
5006 }
5007 c->u->u_col_offset = old_col_offset;
5008 return res;
5009}
5010
5011static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005012compiler_augassign(struct compiler *c, stmt_ty s)
5013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 expr_ty e = s->v.AugAssign.target;
5015 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 switch (e->kind) {
5020 case Attribute_kind:
5021 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005022 AugLoad, e->lineno, e->col_offset,
5023 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 if (auge == NULL)
5025 return 0;
5026 VISIT(c, expr, auge);
5027 VISIT(c, expr, s->v.AugAssign.value);
5028 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5029 auge->v.Attribute.ctx = AugStore;
5030 VISIT(c, expr, auge);
5031 break;
5032 case Subscript_kind:
5033 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005034 AugLoad, e->lineno, e->col_offset,
5035 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 if (auge == NULL)
5037 return 0;
5038 VISIT(c, expr, auge);
5039 VISIT(c, expr, s->v.AugAssign.value);
5040 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5041 auge->v.Subscript.ctx = AugStore;
5042 VISIT(c, expr, auge);
5043 break;
5044 case Name_kind:
5045 if (!compiler_nameop(c, e->v.Name.id, Load))
5046 return 0;
5047 VISIT(c, expr, s->v.AugAssign.value);
5048 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5049 return compiler_nameop(c, e->v.Name.id, Store);
5050 default:
5051 PyErr_Format(PyExc_SystemError,
5052 "invalid node type (%d) for augmented assignment",
5053 e->kind);
5054 return 0;
5055 }
5056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005057}
5058
5059static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005060check_ann_expr(struct compiler *c, expr_ty e)
5061{
5062 VISIT(c, expr, e);
5063 ADDOP(c, POP_TOP);
5064 return 1;
5065}
5066
5067static int
5068check_annotation(struct compiler *c, stmt_ty s)
5069{
5070 /* Annotations are only evaluated in a module or class. */
5071 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5072 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5073 return check_ann_expr(c, s->v.AnnAssign.annotation);
5074 }
5075 return 1;
5076}
5077
5078static int
5079check_ann_slice(struct compiler *c, slice_ty sl)
5080{
5081 switch(sl->kind) {
5082 case Index_kind:
5083 return check_ann_expr(c, sl->v.Index.value);
5084 case Slice_kind:
5085 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5086 return 0;
5087 }
5088 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5089 return 0;
5090 }
5091 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5092 return 0;
5093 }
5094 break;
5095 default:
5096 PyErr_SetString(PyExc_SystemError,
5097 "unexpected slice kind");
5098 return 0;
5099 }
5100 return 1;
5101}
5102
5103static int
5104check_ann_subscr(struct compiler *c, slice_ty sl)
5105{
5106 /* We check that everything in a subscript is defined at runtime. */
5107 Py_ssize_t i, n;
5108
5109 switch (sl->kind) {
5110 case Index_kind:
5111 case Slice_kind:
5112 if (!check_ann_slice(c, sl)) {
5113 return 0;
5114 }
5115 break;
5116 case ExtSlice_kind:
5117 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5118 for (i = 0; i < n; i++) {
5119 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5120 switch (subsl->kind) {
5121 case Index_kind:
5122 case Slice_kind:
5123 if (!check_ann_slice(c, subsl)) {
5124 return 0;
5125 }
5126 break;
5127 case ExtSlice_kind:
5128 default:
5129 PyErr_SetString(PyExc_SystemError,
5130 "extended slice invalid in nested slice");
5131 return 0;
5132 }
5133 }
5134 break;
5135 default:
5136 PyErr_Format(PyExc_SystemError,
5137 "invalid subscript kind %d", sl->kind);
5138 return 0;
5139 }
5140 return 1;
5141}
5142
5143static int
5144compiler_annassign(struct compiler *c, stmt_ty s)
5145{
5146 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005147 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005148
5149 assert(s->kind == AnnAssign_kind);
5150
5151 /* We perform the actual assignment first. */
5152 if (s->v.AnnAssign.value) {
5153 VISIT(c, expr, s->v.AnnAssign.value);
5154 VISIT(c, expr, targ);
5155 }
5156 switch (targ->kind) {
5157 case Name_kind:
5158 /* If we have a simple name in a module or class, store annotation. */
5159 if (s->v.AnnAssign.simple &&
5160 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5161 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005162 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5163 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5164 }
5165 else {
5166 VISIT(c, expr, s->v.AnnAssign.annotation);
5167 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005168 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005169 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005170 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005171 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005172 }
5173 break;
5174 case Attribute_kind:
5175 if (!s->v.AnnAssign.value &&
5176 !check_ann_expr(c, targ->v.Attribute.value)) {
5177 return 0;
5178 }
5179 break;
5180 case Subscript_kind:
5181 if (!s->v.AnnAssign.value &&
5182 (!check_ann_expr(c, targ->v.Subscript.value) ||
5183 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5184 return 0;
5185 }
5186 break;
5187 default:
5188 PyErr_Format(PyExc_SystemError,
5189 "invalid node type (%d) for annotated assignment",
5190 targ->kind);
5191 return 0;
5192 }
5193 /* Annotation is evaluated last. */
5194 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5195 return 0;
5196 }
5197 return 1;
5198}
5199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005200/* Raises a SyntaxError and returns 0.
5201 If something goes wrong, a different exception may be raised.
5202*/
5203
5204static int
5205compiler_error(struct compiler *c, const char *errstr)
5206{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005207 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005209
Victor Stinner14e461d2013-08-26 22:28:21 +02005210 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 if (!loc) {
5212 Py_INCREF(Py_None);
5213 loc = Py_None;
5214 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005215 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005216 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 if (!u)
5218 goto exit;
5219 v = Py_BuildValue("(zO)", errstr, u);
5220 if (!v)
5221 goto exit;
5222 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005223 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 Py_DECREF(loc);
5225 Py_XDECREF(u);
5226 Py_XDECREF(v);
5227 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005228}
5229
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005230/* Emits a SyntaxWarning and returns 1 on success.
5231 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5232 and returns 0.
5233*/
5234static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005235compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005236{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005237 va_list vargs;
5238#ifdef HAVE_STDARG_PROTOTYPES
5239 va_start(vargs, format);
5240#else
5241 va_start(vargs);
5242#endif
5243 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5244 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005245 if (msg == NULL) {
5246 return 0;
5247 }
5248 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5249 c->u->u_lineno, NULL, NULL) < 0)
5250 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005251 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005252 /* Replace the SyntaxWarning exception with a SyntaxError
5253 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005254 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005255 assert(PyUnicode_AsUTF8(msg) != NULL);
5256 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005257 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005258 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005259 return 0;
5260 }
5261 Py_DECREF(msg);
5262 return 1;
5263}
5264
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005265static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266compiler_handle_subscr(struct compiler *c, const char *kind,
5267 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 /* XXX this code is duplicated */
5272 switch (ctx) {
5273 case AugLoad: /* fall through to Load */
5274 case Load: op = BINARY_SUBSCR; break;
5275 case AugStore:/* fall through to Store */
5276 case Store: op = STORE_SUBSCR; break;
5277 case Del: op = DELETE_SUBSCR; break;
5278 case Param:
5279 PyErr_Format(PyExc_SystemError,
5280 "invalid %s kind %d in subscript\n",
5281 kind, ctx);
5282 return 0;
5283 }
5284 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005285 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 }
5287 else if (ctx == AugStore) {
5288 ADDOP(c, ROT_THREE);
5289 }
5290 ADDOP(c, op);
5291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005292}
5293
5294static int
5295compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 int n = 2;
5298 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 /* only handles the cases where BUILD_SLICE is emitted */
5301 if (s->v.Slice.lower) {
5302 VISIT(c, expr, s->v.Slice.lower);
5303 }
5304 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005305 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 if (s->v.Slice.upper) {
5309 VISIT(c, expr, s->v.Slice.upper);
5310 }
5311 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005312 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 }
5314
5315 if (s->v.Slice.step) {
5316 n++;
5317 VISIT(c, expr, s->v.Slice.step);
5318 }
5319 ADDOP_I(c, BUILD_SLICE, n);
5320 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005321}
5322
5323static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5325 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 switch (s->kind) {
5328 case Slice_kind:
5329 return compiler_slice(c, s, ctx);
5330 case Index_kind:
5331 VISIT(c, expr, s->v.Index.value);
5332 break;
5333 case ExtSlice_kind:
5334 default:
5335 PyErr_SetString(PyExc_SystemError,
5336 "extended slice invalid in nested slice");
5337 return 0;
5338 }
5339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005340}
5341
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005342static int
5343compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5344{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005345 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 switch (s->kind) {
5347 case Index_kind:
5348 kindname = "index";
5349 if (ctx != AugStore) {
5350 VISIT(c, expr, s->v.Index.value);
5351 }
5352 break;
5353 case Slice_kind:
5354 kindname = "slice";
5355 if (ctx != AugStore) {
5356 if (!compiler_slice(c, s, ctx))
5357 return 0;
5358 }
5359 break;
5360 case ExtSlice_kind:
5361 kindname = "extended slice";
5362 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005363 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 for (i = 0; i < n; i++) {
5365 slice_ty sub = (slice_ty)asdl_seq_GET(
5366 s->v.ExtSlice.dims, i);
5367 if (!compiler_visit_nested_slice(c, sub, ctx))
5368 return 0;
5369 }
5370 ADDOP_I(c, BUILD_TUPLE, n);
5371 }
5372 break;
5373 default:
5374 PyErr_Format(PyExc_SystemError,
5375 "invalid subscript kind %d", s->kind);
5376 return 0;
5377 }
5378 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379}
5380
Thomas Wouters89f507f2006-12-13 04:49:30 +00005381/* End of the compiler section, beginning of the assembler section */
5382
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005384 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005385
5386 XXX must handle implicit jumps from one block to next
5387*/
5388
Thomas Wouters89f507f2006-12-13 04:49:30 +00005389struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 PyObject *a_bytecode; /* string containing bytecode */
5391 int a_offset; /* offset into bytecode */
5392 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005393 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 PyObject *a_lnotab; /* string containing lnotab */
5395 int a_lnotab_off; /* offset into lnotab */
5396 int a_lineno; /* last lineno of emitted instruction */
5397 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005398};
5399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400static void
T. Wouters99b54d62019-09-12 07:05:33 -07005401dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402{
T. Wouters99b54d62019-09-12 07:05:33 -07005403 int i, j;
5404
5405 /* Get rid of recursion for normal control flow.
5406 Since the number of blocks is limited, unused space in a_postorder
5407 (from a_nblocks to end) can be used as a stack for still not ordered
5408 blocks. */
5409 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005410 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005411 assert(a->a_nblocks < j);
5412 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 }
T. Wouters99b54d62019-09-12 07:05:33 -07005414 while (j < end) {
5415 b = a->a_postorder[j++];
5416 for (i = 0; i < b->b_iused; i++) {
5417 struct instr *instr = &b->b_instr[i];
5418 if (instr->i_jrel || instr->i_jabs)
5419 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005420 }
T. Wouters99b54d62019-09-12 07:05:33 -07005421 assert(a->a_nblocks < j);
5422 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005423 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005424}
5425
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005426Py_LOCAL_INLINE(void)
5427stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005428{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005429 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005430 if (b->b_startdepth < depth) {
5431 assert(b->b_startdepth < 0);
5432 b->b_startdepth = depth;
5433 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005434 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005435}
5436
5437/* Find the flow path that needs the largest stack. We assume that
5438 * cycles in the flow graph have no net effect on the stack depth.
5439 */
5440static int
5441stackdepth(struct compiler *c)
5442{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005443 basicblock *b, *entryblock = NULL;
5444 basicblock **stack, **sp;
5445 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 b->b_startdepth = INT_MIN;
5448 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005449 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 }
5451 if (!entryblock)
5452 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005453 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5454 if (!stack) {
5455 PyErr_NoMemory();
5456 return -1;
5457 }
5458
5459 sp = stack;
5460 stackdepth_push(&sp, entryblock, 0);
5461 while (sp != stack) {
5462 b = *--sp;
5463 int depth = b->b_startdepth;
5464 assert(depth >= 0);
5465 basicblock *next = b->b_next;
5466 for (int i = 0; i < b->b_iused; i++) {
5467 struct instr *instr = &b->b_instr[i];
5468 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5469 if (effect == PY_INVALID_STACK_EFFECT) {
5470 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5471 Py_FatalError("PyCompile_OpcodeStackEffect()");
5472 }
5473 int new_depth = depth + effect;
5474 if (new_depth > maxdepth) {
5475 maxdepth = new_depth;
5476 }
5477 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5478 if (instr->i_jrel || instr->i_jabs) {
5479 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5480 assert(effect != PY_INVALID_STACK_EFFECT);
5481 int target_depth = depth + effect;
5482 if (target_depth > maxdepth) {
5483 maxdepth = target_depth;
5484 }
5485 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005486 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005487 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005488 assert(instr->i_target->b_startdepth >= target_depth);
5489 depth = new_depth;
5490 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005491 }
5492 stackdepth_push(&sp, instr->i_target, target_depth);
5493 }
5494 depth = new_depth;
5495 if (instr->i_opcode == JUMP_ABSOLUTE ||
5496 instr->i_opcode == JUMP_FORWARD ||
5497 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005498 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 {
5500 /* remaining code is dead */
5501 next = NULL;
5502 break;
5503 }
5504 }
5505 if (next != NULL) {
5506 stackdepth_push(&sp, next, depth);
5507 }
5508 }
5509 PyObject_Free(stack);
5510 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005511}
5512
5513static int
5514assemble_init(struct assembler *a, int nblocks, int firstlineno)
5515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 memset(a, 0, sizeof(struct assembler));
5517 a->a_lineno = firstlineno;
5518 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5519 if (!a->a_bytecode)
5520 return 0;
5521 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5522 if (!a->a_lnotab)
5523 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005524 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 PyErr_NoMemory();
5526 return 0;
5527 }
T. Wouters99b54d62019-09-12 07:05:33 -07005528 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005530 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 PyErr_NoMemory();
5532 return 0;
5533 }
5534 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005535}
5536
5537static void
5538assemble_free(struct assembler *a)
5539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 Py_XDECREF(a->a_bytecode);
5541 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005542 if (a->a_postorder)
5543 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005544}
5545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005546static int
5547blocksize(basicblock *b)
5548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 int i;
5550 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005553 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555}
5556
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005557/* Appends a pair to the end of the line number table, a_lnotab, representing
5558 the instruction's bytecode offset and line number. See
5559 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005560
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005561static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005562assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005565 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005567
Serhiy Storchakaab874002016-09-11 13:48:15 +03005568 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 if(d_bytecode == 0 && d_lineno == 0)
5574 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 if (d_bytecode > 255) {
5577 int j, nbytes, ncodes = d_bytecode / 255;
5578 nbytes = a->a_lnotab_off + 2 * ncodes;
5579 len = PyBytes_GET_SIZE(a->a_lnotab);
5580 if (nbytes >= len) {
5581 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5582 len = nbytes;
5583 else if (len <= INT_MAX / 2)
5584 len *= 2;
5585 else {
5586 PyErr_NoMemory();
5587 return 0;
5588 }
5589 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5590 return 0;
5591 }
5592 lnotab = (unsigned char *)
5593 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5594 for (j = 0; j < ncodes; j++) {
5595 *lnotab++ = 255;
5596 *lnotab++ = 0;
5597 }
5598 d_bytecode -= ncodes * 255;
5599 a->a_lnotab_off += ncodes * 2;
5600 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005601 assert(0 <= d_bytecode && d_bytecode <= 255);
5602
5603 if (d_lineno < -128 || 127 < d_lineno) {
5604 int j, nbytes, ncodes, k;
5605 if (d_lineno < 0) {
5606 k = -128;
5607 /* use division on positive numbers */
5608 ncodes = (-d_lineno) / 128;
5609 }
5610 else {
5611 k = 127;
5612 ncodes = d_lineno / 127;
5613 }
5614 d_lineno -= ncodes * k;
5615 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 nbytes = a->a_lnotab_off + 2 * ncodes;
5617 len = PyBytes_GET_SIZE(a->a_lnotab);
5618 if (nbytes >= len) {
5619 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5620 len = nbytes;
5621 else if (len <= INT_MAX / 2)
5622 len *= 2;
5623 else {
5624 PyErr_NoMemory();
5625 return 0;
5626 }
5627 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5628 return 0;
5629 }
5630 lnotab = (unsigned char *)
5631 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5632 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005633 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 d_bytecode = 0;
5635 for (j = 1; j < ncodes; j++) {
5636 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005637 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 a->a_lnotab_off += ncodes * 2;
5640 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005641 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 len = PyBytes_GET_SIZE(a->a_lnotab);
5644 if (a->a_lnotab_off + 2 >= len) {
5645 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5646 return 0;
5647 }
5648 lnotab = (unsigned char *)
5649 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 a->a_lnotab_off += 2;
5652 if (d_bytecode) {
5653 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005654 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 }
5656 else { /* First line of a block; def stmt, etc. */
5657 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005658 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 }
5660 a->a_lineno = i->i_lineno;
5661 a->a_lineno_off = a->a_offset;
5662 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005663}
5664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005665/* assemble_emit()
5666 Extend the bytecode with a new instruction.
5667 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005668*/
5669
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005670static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005671assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005672{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005673 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005675 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005677 arg = i->i_oparg;
5678 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 if (i->i_lineno && !assemble_lnotab(a, i))
5680 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005681 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 if (len > PY_SSIZE_T_MAX / 2)
5683 return 0;
5684 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5685 return 0;
5686 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005687 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005689 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005691}
5692
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005693static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005694assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005697 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 /* Compute the size of each block and fixup jump args.
5701 Replace block pointer with position in bytecode. */
5702 do {
5703 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005704 for (i = a->a_nblocks - 1; i >= 0; i--) {
5705 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 bsize = blocksize(b);
5707 b->b_offset = totsize;
5708 totsize += bsize;
5709 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005710 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5712 bsize = b->b_offset;
5713 for (i = 0; i < b->b_iused; i++) {
5714 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 /* Relative jumps are computed relative to
5717 the instruction pointer after fetching
5718 the jump instruction.
5719 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005720 bsize += isize;
5721 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005723 if (instr->i_jrel) {
5724 instr->i_oparg -= bsize;
5725 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005726 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005727 if (instrsize(instr->i_oparg) != isize) {
5728 extended_arg_recompile = 1;
5729 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 }
5732 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 /* XXX: This is an awful hack that could hurt performance, but
5735 on the bright side it should work until we come up
5736 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 The issue is that in the first loop blocksize() is called
5739 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 So we loop until we stop seeing new EXTENDED_ARGs.
5744 The only EXTENDED_ARGs that could be popping up are
5745 ones in jump instructions. So this should converge
5746 fairly quickly.
5747 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005748 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005749}
5750
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005751static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005752dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005755 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 tuple = PyTuple_New(size);
5758 if (tuple == NULL)
5759 return NULL;
5760 while (PyDict_Next(dict, &pos, &k, &v)) {
5761 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005762 Py_INCREF(k);
5763 assert((i - offset) < size);
5764 assert((i - offset) >= 0);
5765 PyTuple_SET_ITEM(tuple, i - offset, k);
5766 }
5767 return tuple;
5768}
5769
5770static PyObject *
5771consts_dict_keys_inorder(PyObject *dict)
5772{
5773 PyObject *consts, *k, *v;
5774 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5775
5776 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5777 if (consts == NULL)
5778 return NULL;
5779 while (PyDict_Next(dict, &pos, &k, &v)) {
5780 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005781 /* The keys of the dictionary can be tuples wrapping a contant.
5782 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5783 * the object we want is always second. */
5784 if (PyTuple_CheckExact(k)) {
5785 k = PyTuple_GET_ITEM(k, 1);
5786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005788 assert(i < size);
5789 assert(i >= 0);
5790 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005792 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005793}
5794
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005795static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005796compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005799 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005801 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 if (ste->ste_nested)
5803 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005804 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005806 if (!ste->ste_generator && ste->ste_coroutine)
5807 flags |= CO_COROUTINE;
5808 if (ste->ste_generator && ste->ste_coroutine)
5809 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 if (ste->ste_varargs)
5811 flags |= CO_VARARGS;
5812 if (ste->ste_varkeywords)
5813 flags |= CO_VARKEYWORDS;
5814 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 /* (Only) inherit compilerflags in PyCF_MASK */
5817 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005818
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005819 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5820 ste->ste_coroutine &&
5821 !ste->ste_generator) {
5822 flags |= CO_COROUTINE;
5823 }
5824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005826}
5827
INADA Naokic2e16072018-11-26 21:23:22 +09005828// Merge *tuple* with constant cache.
5829// Unlike merge_consts_recursive(), this function doesn't work recursively.
5830static int
5831merge_const_tuple(struct compiler *c, PyObject **tuple)
5832{
5833 assert(PyTuple_CheckExact(*tuple));
5834
5835 PyObject *key = _PyCode_ConstantKey(*tuple);
5836 if (key == NULL) {
5837 return 0;
5838 }
5839
5840 // t is borrowed reference
5841 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5842 Py_DECREF(key);
5843 if (t == NULL) {
5844 return 0;
5845 }
5846 if (t == key) { // tuple is new constant.
5847 return 1;
5848 }
5849
5850 PyObject *u = PyTuple_GET_ITEM(t, 1);
5851 Py_INCREF(u);
5852 Py_DECREF(*tuple);
5853 *tuple = u;
5854 return 1;
5855}
5856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005857static PyCodeObject *
5858makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 PyObject *tmp;
5861 PyCodeObject *co = NULL;
5862 PyObject *consts = NULL;
5863 PyObject *names = NULL;
5864 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 PyObject *name = NULL;
5866 PyObject *freevars = NULL;
5867 PyObject *cellvars = NULL;
5868 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005869 Py_ssize_t nlocals;
5870 int nlocals_int;
5871 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005872 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005873
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005874 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 names = dict_keys_inorder(c->u->u_names, 0);
5876 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5877 if (!consts || !names || !varnames)
5878 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5881 if (!cellvars)
5882 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005883 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 if (!freevars)
5885 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005886
INADA Naokic2e16072018-11-26 21:23:22 +09005887 if (!merge_const_tuple(c, &names) ||
5888 !merge_const_tuple(c, &varnames) ||
5889 !merge_const_tuple(c, &cellvars) ||
5890 !merge_const_tuple(c, &freevars))
5891 {
5892 goto error;
5893 }
5894
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005895 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005896 assert(nlocals < INT_MAX);
5897 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 flags = compute_code_flags(c);
5900 if (flags < 0)
5901 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5904 if (!bytecode)
5905 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5908 if (!tmp)
5909 goto error;
5910 Py_DECREF(consts);
5911 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005912 if (!merge_const_tuple(c, &consts)) {
5913 goto error;
5914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005915
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005916 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005917 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005918 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005919 maxdepth = stackdepth(c);
5920 if (maxdepth < 0) {
5921 goto error;
5922 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005923 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5924 posonlyargcount, kwonlyargcount, nlocals_int,
5925 maxdepth, flags, bytecode, consts, names,
5926 varnames, freevars, cellvars, c->c_filename,
5927 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005928 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 Py_XDECREF(consts);
5930 Py_XDECREF(names);
5931 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 Py_XDECREF(name);
5933 Py_XDECREF(freevars);
5934 Py_XDECREF(cellvars);
5935 Py_XDECREF(bytecode);
5936 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005937}
5938
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005939
5940/* For debugging purposes only */
5941#if 0
5942static void
5943dump_instr(const struct instr *i)
5944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 const char *jrel = i->i_jrel ? "jrel " : "";
5946 const char *jabs = i->i_jabs ? "jabs " : "";
5947 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005950 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5954 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005955}
5956
5957static void
5958dump_basicblock(const basicblock *b)
5959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 const char *seen = b->b_seen ? "seen " : "";
5961 const char *b_return = b->b_return ? "return " : "";
5962 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5963 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5964 if (b->b_instr) {
5965 int i;
5966 for (i = 0; i < b->b_iused; i++) {
5967 fprintf(stderr, " [%02d] ", i);
5968 dump_instr(b->b_instr + i);
5969 }
5970 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005971}
5972#endif
5973
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005974static PyCodeObject *
5975assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 basicblock *b, *entryblock;
5978 struct assembler a;
5979 int i, j, nblocks;
5980 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 /* Make sure every block that falls off the end returns None.
5983 XXX NEXT_BLOCK() isn't quite right, because if the last
5984 block ends with a jump or return b_next shouldn't set.
5985 */
5986 if (!c->u->u_curblock->b_return) {
5987 NEXT_BLOCK(c);
5988 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005989 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 ADDOP(c, RETURN_VALUE);
5991 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 nblocks = 0;
5994 entryblock = NULL;
5995 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5996 nblocks++;
5997 entryblock = b;
5998 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 /* Set firstlineno if it wasn't explicitly set. */
6001 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006002 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6004 else
6005 c->u->u_firstlineno = 1;
6006 }
6007 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6008 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006009 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 /* Can't modify the bytecode after computing jump offsets. */
6012 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006013
T. Wouters99b54d62019-09-12 07:05:33 -07006014 /* Emit code in reverse postorder from dfs. */
6015 for (i = a.a_nblocks - 1; i >= 0; i--) {
6016 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006017 for (j = 0; j < b->b_iused; j++)
6018 if (!assemble_emit(&a, &b->b_instr[j]))
6019 goto error;
6020 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6023 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006024 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006027 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006028 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 assemble_free(&a);
6030 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006031}
Georg Brandl8334fd92010-12-04 10:26:46 +00006032
6033#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006034PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006035PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6036 PyArena *arena)
6037{
6038 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6039}